I need my script to do something on the first time an element is clicked and continue to do something different on click 2,3,4 and so on
$('selector').click(function() {
//I would realy like this variable to be updated
var click = 0;
if (click === 0) {
do this
var click = 1;
} else {
do this
}
});//end click
really I think it should rely on the variables but I can't think of how to update the variable from here on out any help would be awesome.
Use data to persist your state with the element.
In your click handler,
use
to retrieve the value and
to set it.
Note: $(this).data('number_of_clicks') will return false if it hasn't been set yet
Edit: fixed link
Have a look at jQuery's
.data()
method. Consider your example:See a working example here: http://jsfiddle.net/uaaft/
$('#foo').one('click', function() { alert('This will be displayed only once.'); });
this would bind click event to Corresponding Html element once and unbind it automatically after first event rendering.
Or alternatively u could the following:
$("#foo").bind('click',function(){
// Some activity
$("#foo").unbind("click"); // bind it to some other event handler.
});
Another alternative might be to have two functions, and bind one using the
one
function in$(document).ready()
(or wherever you are binding your handlers), and in that function, bind the second function to be run for all subsequent clicks usingbind
orclick
.e.g.
If you just need sequences of fixed behaviors, you can do this:
$('selector').toggle(function(){...}, function(){...}, function(){...},...);
Event handlers in the toggle method will be called orderly.
This is super easy in vanilla Js. This is using proper, different click handlers
Documentation, CanIUse