How to mark/deselect a link on a page by clicking on next/back?

Asked

Viewed 114 times

3

Would like to mark and cancel one "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 receives stylization CSS .ativo pointing out where the countdown is.


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

2 answers

4


Well, the simplest way I imagined is to keep the counter from the current position and go regressing or increasing according to the click.

Let’s go in pieces:

First, we will have our counter that initially will have the value of 0. He will be responsible to show the position of the current link.

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

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 made just one example that I find more didactic.

Once this is done, we have the starting position and how far he 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 function mudaSeta(), that is responsible for changing the position of the active class. This change will be made in 3 steps. Check which side to go through, remove the active class from the previous one and add to the new one.

To check the side I added a side parameter in the function mudaSeta(). This 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 the function I check which way I will go. If it goes left, I remove 1 from the counter if it goes right, I add. This value removed or added is the value referring to the position of the link on the page (that link variable we set at the beginning (var link)).

The function mudaLado() was 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 just check the side, do a conditional check to check if it is not in the last element and subtract or add 1 in 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 explain better what you said.

As I have said too much, 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>

  • I am adding the explanation at this point. I posted only the result to advance you.

  • @Diegohenrique Just copy and paste into your code :p

  • @Diegohenrique He has compatibility with almost all browsers

3

I did it with jquery, and commented on the code. That would be?

// 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>
<span id="voltar">&#171</span>

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

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

  • 1

    It was even good, and yes it was really that. But I hoped in Javascript because I do not understand yet Jquery

Browser other questions tagged

You are not signed in. Login or sign up in order to post.