Jquery if its the first time element is being clicked

Luis picture Luis · Jan 14, 2011 · Viewed 7k times · Source

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.

Answer

treeface picture treeface · Jan 14, 2011

Have a look at jQuery's .data() method. Consider your example:

$('selector').click(function() {
    var $this = $(this),
        clickNum = $this.data('clickNum');

    if (!clickNum) clickNum = 1;

    alert(clickNum);

    $this.data('clickNum', ++clickNum);
});

See a working example here: http://jsfiddle.net/uaaft/