0

I've made a script which calls a function every 5 clicks on an element. What I'd like to do now is to repeat the action every 5 clicks, and not just call it only once. Is there any way to reset the variable count when the action is called?

$(document).ready(function(){
var count=0;
$(".logo").click(function(){
    count+=1;
    if (count==5) {
        $( "body" ).toggleClass('easteregg');
    }
  });
});

2 Answers2

5

you don't have to reset it just do

if(count % 5 === 0){
    //your code here
}

This will be called every time the count is multiple of 5

forJ
  • 4,309
  • 6
  • 34
  • 60
  • Thanks for your answer, but I don't fully understand how this works. Could you explain please? I'm a newbie in Javascript. –  Aug 18 '17 at 00:54
  • @Dimitris1337 sure. '%' means divide the `count` and return remainders. So in this code if you divide count by 5 and if the remainder is 0, it means the count is a multiple of 5, hence every 5 clicks. – forJ Aug 18 '17 at 00:55
  • So it should be something like this? $(document).ready(function(){ var count=0; $(".logo").click(function(){ if (count % 5 === 0) { $( "body" ).toggleClass('easteregg'); } }); }); –  Aug 18 '17 at 00:57
  • if you want an in depth explanation of the mod % operator: https://stackoverflow.com/questions/17524673/understanding-the-modulus-operator – The4thIceman Aug 18 '17 at 00:59
  • @Dimitris1337 yes. The structure is hard to recognize in one line but if you just change the `count ==5` part to `count % 10 === 0`. It will fire every 10 counts. Also, `===` means do not force type coercion so if you want to be strict it is safer to use `===` than `==` – forJ Aug 18 '17 at 00:59
0

Why not reset the counter after the action?

$(document).ready(function(){
var count=0;
$(".logo").click(function(){
    count+=1;
    if (count==5) {
        $( "body" ).toggleClass('easteregg');
        count = 0;
    }
  });
});
NuttLoose
  • 665
  • 7
  • 11