JQuery if its first time element is clicked

I need my script to do something the first time the element clicks and continues to do something else when clicking 2,3,4, etc.

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

Actually, I think it should rely on variables, but I can't figure out how to update the variable here, any help would be awesome.

+5
source share
6 answers

Take a look at the jQuery method .data(). 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/

+10
source

Use data to save your state with an element.

$().data( 'NUMBER_OF_CLICKS')

$().data( 'NUMBER_OF_CLICKS', some_value)

.

: $(this).data('number_of_clicks') false,

:

+9

, one $(document).ready() ( , ), , , bind click.

.

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);
});
+1

, :

$('selector'). toggle (function() {...}, function() {...}, function() {...},...);

.

0

$('# foo'). one ('click', function() { alert (' .'); });

click Html .

, , :

$( "# Foo" ). Bind ('click', () {

//

$( "# Foo" ) ("click"). // .

});

0

vanilla Js. ,

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

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

, CanIUse

0

All Articles