rewind the click counter signaling where it left off

1

I tried to create a progressive and regressive counter to mark that tag is stopped.

Code

el = document.getElementsByTagName('a')

var x = 0,
    y = 0;

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

    x--;

    if (y == 3 || x == 0)
        alert("Limite!");
    else {
        el[x].className = 'ativo';
        el[y].className = '';
    }
    y++;
}


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

    x++;

    if (y == 3 || x == 4)
        alert("Limite!");
    else {
        el[y].className = '';
        el[x].className = 'ativo';
    }
    y++;
}
a {
  cursor: pointer; padding: 3px; text-decoration: none; color: #111;
}
a.ativo {
  font-weight: bolder;
  background-color: #333;
  color: #fff;
}
<button id="menos">&#171 Anterior</button>

<a href="#A" class="ativo" >1</a>
<a href="#B">2</a>
<a href="#C">3</a>
<a href="#D">4</a>

<button id="mais">Próximo &#187</button>

   
  

See that backing up the counter does not work as expected, it would be the same as moving forward, hopping one-on-one home. I made several changes and it did not work.

I need you to help me solve this small misunderstanding. Go back the same way you went signaling one by one

    
asked by anonymous 30.05.2016 / 22:00

2 answers

3

I think you can simplify your code for this:

var els = document.getElementsByTagName('a')
var btns = document.getElementsByTagName('button')
var x = 0;

for (var i = 0; i < btns.length; i++) {
    btns[i].addEventListener('click', mudarPágina);
}

function mudarPágina() {
    for (var i = 0; i < els.length; i++) { // fazer reset
        els[i].classList.remove('ativo');
    }
    var incr = this.id == 'mais' ? 1 : -1;
    x = x + incr;
    if (x < 0) x = 0;
    else if (x > els.length - 1) x = els.length - 1;
    els[x].classList.add('ativo');
}

jsFiddle: link

So it gets less repetitive, you have the whole logic in one function, and you just need to read the% mais id to know which direction to take.

    
30.05.2016 / 22:09
0

In addition to the @Sergio answer I leave another alternative, with a short modification in my Source Code / strong>.

This script , in turn, works on any version of browsers, from old to current. Check out:

Code

el = document.getElementsByTagName('a')

var x = 0, y = 0;

function voltar()
{
  
  if(x == 0) x = alert("Limite!");

for(var i = 0; i < el.length; i++){
  el[i].className = "";
}
  el[x].className = "color";
  
  x--;

}
function avancar()
{
if(y == 5 || x == 6) y = alert("Limite!");
else {
el[y].className = "";
el[x].className = "color";
}
y++;
}
a
{ 
text-decoration: none;

cursor: pointer;

padding: 3px; 

color: black; 
}

a.color {
  color:red;
  }
<a onclick="voltar(5)" id="menos">&#171 Anterior</a>

<a>1</a>
<a>2</a>
<a>3</a>
<a>4</a>
<a>5</a>

<a onclick="avancar(x++)" id="mais">Próximo &#187</a>
    
29.06.2016 / 18:06