Lewis
Lewis

Reputation: 14866

jQuery - check if first click

I have 2 functions (A and B) called on a single div click. I need to call function A only on first click and function B whenever it is clicked. How could I do this?

Upvotes: 7

Views: 6426

Answers (3)

Juan
Juan

Reputation: 5050

You can add the first function on page load, that way that function gets called with the first click, at the end of the function you use off() to remove the first function and then assign the second one.

$(function(){
    $("selector").on("click",FunctionA);
});

function FunctionA(){
    /*Do stuff*/
    $(this).off("click");
    $(this).on("click",FunctionB);
}

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

Much simpler solution:

$('element').one('click',function(){
// Call A
}).click(function(){
// Call B
});

Upvotes: 8

Felix
Felix

Reputation: 38102

You can use .one() for your first function and .click() as usual for your second function:

function a() {
    console.log('Fire once!');
}

function b() {
    console.log('Always fired!');
}

$('span').one('click', function() {
    a();    
});

$('span').click(function() {
    b();    
});

Fiddle Demo

Upvotes: 0

Related Questions