Question

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.

Was it helpful?

Solution

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/

OTHER TIPS

Use data to persist your state with the element.

In your click handler,

use

$(this).data('number_of_clicks')

to retrieve the value and

$(this).data('number_of_clicks',some_value)

to set it.

Note: $(this).data('number_of_clicks') will return false if it hasn't been set yet

Edit: fixed link

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 using bind or click.

e.g.

function FirstTime(element) {
   // do stuff the first time round here
   $(element.target).click(AllOtherTimes);
}

function AllOtherTimes(element) {
   // do stuff all subsequent times here
}

$(function() {
    $('selector').one('click', FirstTime);
});

This is super easy in vanilla Js. This is using proper, different click handlers

const onNextTimes = function(e) {
    // Do this after all but first click
};

node.addEventListener("click", function onFirstTime(e) {
    node.addEventListener("click", onNextTimes);
}, {once : true});

Documentation, CanIUse

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.

$('#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.

});

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