Alternative to jquery toggle. Code explanation

Alternative to jquery toggle. Code explanation
0.0 0

#1

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.


#2
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


#3

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]


#4

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