After asking the same question 2 weeks ago here, I finally found "the" solution. This is why I am answering my own question. ;)
HOW TO BIND, UNBIND AND REBIND EVENTS IN JQUERY?
Use the off() method instead. The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.
jQuery bind() function is used to attach an event handler to elements, while the unbind() is used to detached an existing event handler from elements.
bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs. For more flexible event binding, see the discussion of event delegation in .
In short: . bind() will only apply to the items you currently have selected in your jQuery object. . live() will apply to all current matching elements, as well as any you might add in the future.
And THIS is the perfect solution. (At least for me.)
$(document).on('click', 'a#button', function(){
$(this).after('<span> hello</span>');
$('span').fadeOut(1000);
});
$('a#toggle').toggle(
function(){
$(this).text('rebind');
$('a#button').on('click.disabled', false);
},
function(){
$(this).text('unbind');
$('a#button').off('click.disabled');
}
);
".on()" does it. NOTE: It is important to bind the event like you can see on line one! It does not work with .click() or …!
See the docs!
Here is a fiddle to try it and experiment with it!
Enjoy!
A simpler and short solution is to add a class to the object if you want to unbind it then remove this class to rebind ex;
$('#button').click( function(){
if($(this).hasClass('unbinded')) return;
//Do somthing
});
$('#toggle').click(function(){
$('#button').toggleClass('unbinded');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With