Question

<div id="element1" onclick="func();">1</div>
<div id="element2" onclick="func();">2</div>
<div id="element3" onclick="func();">3</div>
<div id="element4" onclick="func();">4</div>
<div id="element5" onclick="func();">5</div>
<div id="element6" onclick="func();">6</div>
<div id="element7" onclick="func();">7</div>
<div id="element8" onclick="func();">8</div>

When user click any div, func() function will work and a counter calculate how many times process func() function. For example 2 times (we determine the number) process func() function than when user click any div again function will not work. How can I do this with jquery?

Was it helpful?

Solution

Use a global variable to track the number of times the function is called.

var counter = 0;

function func() {

    counter++;
    if (counter > 2) return;

    // do other fn stuff
}

On a slightly related note, there is a better way of binding multiple click handlers when using jQuery:

$('div[id^="element"]').click( func );

Of course, it doesn't really matter since return will halt execution, but if you didn't want func to be called at all (i.e. if you wanted to remove the click event altogether), you could then simply do (if you make the change above):

$('div[id^="element"]').unbind('click');

This would be in place of the return statement in the first section of code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top