Daniel Böhmer
Daniel Böhmer

Reputation: 15381

jQuery .one() with same function for different events on different elements

I have an introduction on my page which shall disappear when a key is pressed or a certain elements is clicked on. I'll use the same function for both events but as the page is heavily modified the event shall fire only once regardless which way it was triggered.

My function:

function start() {
    $('.intro').remove();
    $('.something-else').show();
}

How I bind the events:

$('body').keypress(start);
$('.intro').click(start);

If the events were the same I could say

$('body, .intro').one('click', start);

If both events were to happen to the same element I could say:

$('.intro').one('click keypress', start);

How to combine both things: having different elements and different events and the function must only be called once?

Upvotes: 1

Views: 176

Answers (3)

veritasetratio
veritasetratio

Reputation: 611

I don't think this solution is a clean as an explicit approach, but is done using a combination of .one() and .trigger(). Because you call $(".intro").remove() on one of the bound items the event handler is implicitly unbound. Sample Fiddle

Excluding the html seen in fiddle, this is the code.

// Your event handler
function start() {
    $("#intro").remove();
    $("#main").show();
    console.log("start handler called");
}

// Handle the keypress event
$("body").one( "keypress", start );

// Allow user to click through the intro, but trigger the keypress handler on the body which is a one-time event handler)
$("#intro").one( "click", function () { $("body").trigger( "keypress" ); });

Upvotes: 0

landons
landons

Reputation: 9547

Use two lines of code and be done ;)

$('body').one('keypress', start);
$('.intro').one('click', start);

Edit: You should manually unbind the other callback, lest it runs later, unexpectedly.

Upvotes: 0

Sascha Gehlich
Sascha Gehlich

Reputation: 1007

The simplest solution would be to store whether your function has been called or not.

var started = false;
function start() {
    if(started) return;

    $('.intro').remove();
    $('.something-else').show();

    started = true;
}

Then your function can only be called once, every other call will be ignored.

Upvotes: 1

Related Questions