TrySpace
TrySpace

Reputation: 2460

jQuery.bind unbind, multiples instances of classes

I have multiple elements with the same class "clickable", i'm binding all these classes with:

 $('.clickable').bind('click', function()
     { 
       $(this.id).html('clicked');

     }

I'm assuming the bind binds each element with the class "clickable" individually. Then within this bind-function, I want to unbind the currently clicked element with:

 $(this.id).unbind('click');

So that if you click again within this element, it doesn't trigger the click-function again. And then, after doing stuff within the element (replace the text withing these elements with an that puts the current text in it, and when you click outside it it wil alter the html for it) I want to rebind the click again, but I cant't seem to unbind the click for this.id...

Some fiddle for clarification: http://jsfiddle.net/TrySpace/QZMP6/7/

Upvotes: 0

Views: 621

Answers (2)

Andrew Whitaker
Andrew Whitaker

Reputation: 126072

Probably because your selector is wrong (because your selector would translate to something like $("my_id") when you really want $("#my_id")). In this case, you could just do:

$(this).unbind('click');

Which is ultimately better than querying the DOM again for an element.

Side note: bind and unbind are deprecated as of jQuery 1.7. The updated way to write this is with on and off:

$(".clickable").on("click", function () {
    /* ... */
    $(this).off("click");
});

Edit (per comments below):

If you want to prevent parent event handlers from being notified as well, you could bind a new handler that prevents propagation of the event:

$(this).off("click").on("click", function (e) {
    e.stopPropagation();
});

Upvotes: 4

user1106925
user1106925

Reputation:

You may want to consider jQuery's selector based event delegation, and just remove the 'clickable' class when clicked...

$('body').on('click', '.clickable', function() { 
    $(this).html('clicked')
           .removeClass('clickable');
});

Or in pre-jQuery 1.7, but post 1.4 or so...

$('body').delegate('.clickable', 'click', function() { 
    $(this).html('clicked')
           .removeClass('clickable');
});

In both cases, I placed the delegate handler on the 'body', but it would be better to place it on a more local element, as long as it encompasses all the .clickable elements.

Upvotes: 1

Related Questions