user1464853 user1464853 - 1 year ago 74
Javascript Question

get previous selected list item index and compare to current

I have a list as pagination dots for a carousel. Each selected item adds a selected class and I can easily get the index of that list item.

I need to be able to compare the current selected list item index with that of the previously selected list item index so I can determine if I need to add any animation to them.

Ideally I want to be in a position to do the following

if(currentIndex > 3 && currentIndex > oldIndex)
{do stuff}

Answer Source

Create a variable that will store the old index. When the next item is selected, use the value of that variable to do what you want. When you're done, assign the new position to the variable. When the user selects again, that will be the old index.

I don't know your code, so I hope you understand:

var oldIndex = -1; // -1 indicates that the user hasn't yet selected any item
$('.all-the-items').click(function () {
  var currentIndex = $(this).index();
  if (oldIndex === -1) {
    // the user has selected for the first time
  } else {
    // oldIndex holds the old index, currentIndex holds the current index
    // do stuff with oldIndex and currentIndex
    if(currentIndex > 3 && currentIndex > oldIndex) {
      // ...
    }
  }
  oldIndex = currentIndex; // set the old index to the current index
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download