Pierre Georges Pierre Georges - 7 months ago 75
Javascript Question

Detect second click on button

I want to change CSS on a button. On the first click, and on the second.
I have this but it doesn't work. Never add .clic-two

$(".prev-next-links li.no-clic").click(function() {
$(this).removeClass('no-clic');
$(this).addClass('clic-one');
});

$(".prev-next-links li.clic-one").click(function() {
$(this).removeClass('clic-one');
$(this).addClass('clic-two');
});

Answer

Another way of doing it is by using the common class as the selector. Since the DOM is dynamic you would have to use the CSS class that is not changing after a user interaction.

$(".prev-next-links, .prev-next-links a").click( function() {

   if ($(this).hasClass("no-clic")) {
 
     $(this).removeClass('no-clic');
     $(this).addClass('clic-one');
   } else if ($(this).hasClass("clic-one")) {
     $(this).removeClass('clic-one');
     $(this).addClass('clic-two');
   }



 });
.prev-next-links {
  font-weight: bold;
}
.no-clic {
  background-color: gray;
}
.clic-one {
  background-color: aqua;
}
.clic-two {
  background-color: lime;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="prev-next-links no-clic">First
  </li>
  <li class="prev-next-links"><a class="no-clic" href="#">Second</a>
  </li>

</ul>