Skip to content
Advertisement

jQuery unbind after first click

This causes multiple buttons to take action:

$(document).on("click", ".file-this-email", fileThisEmail);

When fileThisEmail runs, I’d like to remove it from ONLY the current one (there are others on the page that still need it):

window.fileThisEmail = function(e) {
  console.log('this was clicked');
}

I tried off, but couldn’t seem to get it right. Any ideas?

Advertisement

Answer

In this case, you have to make the current element no longer match the ".file-this-email" selector.

$(document).on("click", ".file-this-email", function() {
    console.log('this was clicked');
    $(this).removeClass("file-this-email");
});

An alternative would be to add a filter to the selector, with the same concept.

$(document).on("click", ".file-this-email:not(.clicked)", function() {
    console.log('this was clicked');
    $(this).addClass("clicked");
});

Or, don’t use delegation for this particular case. Delegation isn’t some new technology that replaces direct binding, it’s just another way of binding events. If used correctly, it can make code more efficient. The opposite is true too; if used incorrectly, it can make the code very bloated.

$(".file-this-email").on("click", function () {
    console.log("this was clicked");
    $(this).off("click");
});
// or even better (thanks @overachiever):
$(".file-this-email").one("click", function () {
    console.log("this was clicked");
});
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement