Bind a handler only once for all elements of the class

How to associate the click event with the .myclass class so that the handler runs only once for all .myclass elements and does not execute again if the user clicks on another .myclass element.

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

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

thank

+4
source share
2 answers

Remove the event handler on first click

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

    // do stuff

});

Using events with names , make sure that you delete only this handler and not other click handlers.

Fiddle

+5
source

You can use the delegated form one () :

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

adeneo fiddle.

+1

Source: https://habr.com/ru/post/1535366/


All Articles