MrJoshFisher MrJoshFisher - 20 days ago 6
jQuery Question

How do I loop through divs with left and right buttons?

Im trying to loop through 6 divs with the left and right buttons, the idea is that you can move left and right and the selected div would have the class 'active' and then when you click left or right it would move to the next div along and remove the class from the previous div and add it to the next one along the line.

This is my Js

$(function () { // this is a shortcut for document ready
var stuff = ['box1', 'box2', 'box3', 'box4', 'box5','box6'],
counter = 0;

console.log(stuff[counter]); // your initial value


$('.right').click(function () {
counter = (counter + 1) % stuff.length;
valueNw = stuff[counter];
console.log(valueNw);
});
$('.left').click(function () {
counter = (counter - 1) % 1;
console.log(stuff[counter]);
});


});


codePen

Any ideas would be appreciated, I've got it to go forwards but not backwards, if there is a better way of doing this please let me know.

Answer

In your code (counter - 1) % 1 would always result 0 so it always points to 0. Instead, change the backward condition to avoid negative values by replacing value to stuff.length in case counter is 0.

$(function() { // this is a shortcut for document ready
  var stuff = ['box1', 'box2', 'box3', 'box4', 'box5', 'box6'],
    counter = 0;

  console.log(stuff[counter]); // your initial value


  $('.right').click(function() {
    counter = (counter + 1) % stuff.length;
    valueNw = stuff[counter];
    console.log(valueNw);
  });
  $('.left').click(function() {
    // replace with stuff.length if counter holds 0 and decrement
    counter = (counter || stuff.length) - 1;
    console.log(stuff[counter]);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="right">right</button>
<button class="left">left</button>

Comments