Alternative to jquery toggle. Code explanation

Hello,
I was looking for alternative of jquery toggle and came across this code:

$('a').click(function() {
  var clicks = $(this).data('clicks');
     if (clicks) {
       alert('odd number of clicks');
    } else {
      alert('even number of clicks');
       }
   $(this).data("clicks", !clicks);
});

I tried it and it works, but I can’t figure out what it does. I see that it creates a variable that hold data in my element. However, I don’t understand the rest of the code. Esp. I don’t understand what this line $(this).data(“clicks”, !clicks); does.

var link = document.getElementsByTagName('a');
link.addEventListener('click', function() {
   if(true) {
     alert('odd number of clicks');
   } else {
      alert('even number of clicks');
   }
});

When you click the link, something should happen, else something else. Something like this…

For your var clicks, to not be undefined, setting to !clicks will evaluate to false, and when you click the second time it will evaluate to true

The ‘not’ operator (!) will return a boolean value of false or true, depending on the value of the variable it works on.

Run this in an html file and see:

[code][/code]

1 Like

Thanks a lot! Great explanation :slight_smile: Now it makes sense!!