How do I mark / unmark a link on a page by clicking on next / previous page?

3

I would like to tag and uncheck a "link " on a page ...

Example

var contar = 0; 

link = document.getElementsByTagName('a')


// Rotina Do Botão Próximo 

document.getElementById('frente').onclick = function(){

contar++;

if (contar == 1) { 
 
link[0].className = ''; link[contar].className = 'ativo';
 
} else if (contar == 2) {

link[1].className = ''; link[contar].className = 'ativo';

} else if (contar == 3) {

link[2].className = ''; link[contar].className = 'ativo';

} else { return  }
}


// Rotina Do Botão Anterior

document.getElementById('voltar').onclick = function(){

contar--;

if (contar == 1) {  

link[0].className = 'ativo'; link[contar].className = '';
  
} else if (contar == 2) {

link[1].className = 'ativo'; link[contar].className = ''; 

} else if (contar == 3) {

link[2].className = 'ativo'; link[contar].className = ''; 

} else { return }
}
.ativo { color:red; }

a:hover { color: red; }
<a id="voltar">&#171</a>

<a>1</a>
<a>2</a>
<a>3</a>

<a id="frente">&#187</a>
  

Each link gets CSS stylization .ativo pointing where the count is stopped.


So I want to automate this script , leaving your syntax clean , without there being any need to quantify clicks . In other words it would be modify to something more exuto.

    
asked by anonymous 02.01.2017 / 21:08

2 answers

4

Well, the simplest way I've imagined is to keep the counter from the current position and go back up or down according to the click.

Let's break it down:

Firstly, we will have our counter that initially will have the value of 0. It will be responsible for showing the position of the current link.

Second, we have to get all the links. For this I have used querySelectorAll () . The choice was because I want to avoid the elements responsible for "changing" pagination, that is, the little ones. To remove the arrows, I added the .seta class in these elements and in the selector, just use :not() , like this:

var links = document.querySelectorAll('a:not(.seta)');
  

There are other options to do this, such as adding the class only in the list, using the first and last element, and whatever else you want. I just did an example that I find more didactic.

Once this is done, we have the starting position and how far it can go ( links.length ).

The next step is to create the function responsible for changing the active link, which is the real reason for the question.

For this, I created the mudaSeta() function, which is responsible for changing the position of the active class. This change will be made in 3 steps. Check the side to go, remove the active class from the previous one and add it to the new element.

To check the side I added a side parameter in the mudaSeta() function. That way I add this parameter when calling the function. To be easier to exemplify, the parameters are and and d (left and right). So, in function I check which side I will go to. If it is to the left, I remove 1 from the counter if it is to the right, I add. This value removed or added is the value relative to the position of the link on the page (that link variable we defined at the beginning ( var link )).

The function mudaLado() is as follows:

function mudaSeta(lado) {
  if (lado == 'e') {
    if (contador > 0) {
      links[contador].classList.remove("ativo");
      contador--;
      links[contador].className += " ativo";
    }
  } else {
    if (contador < links.length - 1) {
      links[contador].classList.remove("ativo");
      contador++;
      links[contador].className += " ativo";
    }
  }

  console.log(contador)
}

Note that I only check the side, I make a conditional check to check if it is not in the last element and I subtract or add 1 to the counter. After that, just get the element by the position and add the active class. But specifically, this way:

  //Removo a classe do elemento anterior
  links[contador].classList.remove("ativo");
  //Adiciono ou subtraio 1 do contador
  contador--;
  //Adiciono a classe ativo no novo elemento
  links[contador].className += " ativo";

The above comments better explain what you said.

As I said before, see the example below, I think it will be simpler to understand.

var contador = 0;
var links = document.querySelectorAll('a:not(.seta)');

function mudaSeta(lado) {
  if (lado == 'e') {
    if (contador > 0) {
      links[contador].classList.remove("ativo");
      contador--;
      links[contador].className += " ativo";
    }
  } else {
    if (contador < links.length - 1) {
      links[contador].classList.remove("ativo");
      contador++;
      links[contador].className += " ativo";
    }
  }

  console.log(contador)
}
.ativo {
  color: red;
}
a:hover {
  color: red;
}
.seta {
  cursor: pointer;
}
<a class="seta" onclick="mudaSeta('e')">&#171</a>

<a class="ativo">1</a>
<a>2</a>
<a>3</a>
<a>4</a>
<a>5</a>
<a>6</a>

<a class="seta" onclick="mudaSeta('d')">&#187</a>
    
02.01.2017 / 21:47
3

I did it with jquery, and I commented the code. Is that it?

// ao clicar na seta de voltar
$("#voltar").on('click',function(){
//pega o conteudo do <a> que esta atualmente ativo
 var valor=+$(".ativo").html(); 
// percorre todos os links para encontrar qual esta ativo
$("a").each(function(){
// verifica se esse é o link anterior, que vai ficar ativo e se é maior ou igual a 1
if($(this).html()==(valor-1) && (valor-1)>=1 ){
 //removo a classe do atual link ativo
 $(".ativo").removeClass("ativo");  
// adiciono a classe no atual (no caso, o link anterior)
$(this).addClass("ativo");
}

});
                
});
// ao clicar na seta de avançar
$("#frente").on('click',function(){
 //pega o conteudo do <a> que esta atualmente ativo
  var valor=+$(".ativo").html(); 
 //pega o numero total de links
   var total= $("a").length;
//percorre todos os links para encontrar qual esta ativo e definir o proximo como ativo
$("a").each(function(){
 // verifica se esse é o proximo link, que vai ficar ativo e se é menor ou igual ao total dde links
if($(this).html()==(valor+1) && valor+1<=total){ 
 //removo a classe do atual link ativo
 $(".ativo").removeClass("ativo");  
// adiciono a classe no atual (no caso, o link anterior)
$(this).addClass("ativo");

}

});
 // ao clicar em qualquer numero eu defino ele como ativo e removo o que estava ativo 
$("a").on('click',function(){
 $(".ativo").removeClass("ativo");  
$(this).addClass("ativo");
});
                
});
.ativo { color:red; }

a:hover { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><spanid="voltar">&#171</span>

<a>1</a>
<a class="ativo">2</a>
<a>3</a>
<a>4</a>

<span id="frente">&#187</span>
    
02.01.2017 / 21:51