back the click counter signaling where it stopped

Asked

Viewed 70 times

1

I tried to create a progressive and regressive counter to mark on what tag this 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>

   

Note that reverse the counter, does not work in an expected way, which would be equal to advancing, jumping from one-on-one house. I’ve made several modifications and resulted in nothing.

I need you to help me solve this little misconception. Go back the way you went forward signaling of one in one

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: https://jsfiddle.net/pye0p7fz/1/

So it’s less repeated, you have all the logic in one function and you only need to read the id mais menos to know which direction to take.

0

In addition to the response of @Sergio I leave another alternative, with a brief modifying in my Source Code included in the Question.

This script in turn, it 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>

Browser other questions tagged

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