Louis
Louis

Reputation: 2608

Bind handler only once for all elements of a class

How to bind a click event to a class .myclass, so that the handler is executed only once for all .myclass elements, and not executed again if the user clicks on another .myclass element.

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

will execute the handler once per .myclass element, but I need the handler to be executed once, for all .myclass elements.

Thanks

Upvotes: 4

Views: 914

Answers (2)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263047

You can use the delegated form of one():

$(document).one("click", ".myclass", function() {
    // ...
});

I modified adeneo's fiddle to demonstrate this.

Upvotes: 0

adeneo
adeneo

Reputation: 318302

Remove the event handler on first click

$('.myclass').on('click.custom', function () {
    $('.myclass').off('click.custom');

    // do stuff

});

using namespaced events makes sure you remove that handler only, and not other click handlers.

FIDDLE

Upvotes: 6

Related Questions