Dylan Hsiao Dylan Hsiao -4 years ago 86
HTML Question

detect clicking different index of the same class or element

I have a navigation with ul li in it

<nav>
<ul>
<li id="zero"></li>
<li id="one"></li>
<li id="two"></li>
</ul>
</nav>


for javascript I have event handler to detect the index I click on. But how do I write a if condition if the current click on the li is different from the previous one?

$('li').click(function(){
var indexNum = $(this).index();
if( prevIndexNum != currentIndexNum ){
//do something
}
})


I guess this is more of a question on how to store the previous variable value? Any read on it greatly appreciated.

Answer Source

You just need to save off the last one clicked.

var prevIndexNum;

$('li').click(function() {
  var indexNum = $(this).index();
  if (prevIndexNum !== indexNum) {
    console.log('different');
    prevIndexNum = indexNum;
  } else {
    console.log('same');
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li id="zero">zero</li>
  <li id="one">one</li>
  <li id="two">two</li>
</ul>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download