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

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

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?

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) {
    prevIndexNum = indexNum;
  } else {
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <li id="zero">zero</li>
  <li id="one">one</li>
  <li id="two">two</li>

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