Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show previous items in array with Jquery

I have this script that shows the next 16 items in the array. But i want it to show the previous 16 when the "back" button is clicked.

This is the script i'm using for the "Next" button:

var YearList = $('.dateListItem li').toArray();

var index = 0;

displayNext();

$(".arrowRight").click(function() {
  // display next elements
  displayNext();
});

function displayNext() {
  $(YearList).hide();

  var list = $('.dateListItem');
  var index = list.data('index') % YearList.length || 0;

  list.data('index', index + 2);
  $(YearList.slice(index, index + 2)).show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="arrowRight">NEXT</a>

<ul class="dateListItem">
  <li>1978</li>
  <li>1979</li>
  <li>1980</li>
  <li>1981</li>
  <li>1982</li>
  <li>1983</li>
</ul>

So now i just need it to go the other way as well.

Thank you for any assistance.

like image 858
WebStar101 Avatar asked Mar 30 '26 17:03

WebStar101


1 Answers

You can replace this js code with yours,

var YearList = $('.dateListItem li').toArray();

var index = 0;

displayNext();

$(".arrowRight").click(function() {
  // display next elements
  displayNext();
});

$(".arrowLeft").click(function() {
  // display next elements
  displayPrev();
});

function displayNext() {
  $(YearList).hide();

  var list = $('.dateListItem'); 
  var index = list.data('index') % YearList.length || 0;

  list.data('index', index + 16);             
  $(YearList.slice(index, index + 16)).show(); 
}

function displayPrev() {
  $(YearList).hide();

  var list = $('.dateListItem'); 
  var index = list.data('index') % YearList.length || 0;
  index = index - 16;
  list.data('index', index);             
  $(YearList.slice(index - 16, index)).show(); 
}

And working jsfiddle here it is.

like image 141
Rahul Avatar answered Apr 02 '26 02:04

Rahul