Remove unbind attribute in jquery
I disabled the image click event using the unbind method. But I don't know yet how to restore the click event. Here is the code,
<img src="testimg.jpg" id="sub_form">
disabled click event over image using code
$('#sub_form').unbind('click');
How do I restore the click event? I tried with bind event
$('#sub_form').bind('click');
but it won't work.
Why am I dispatching the click event for the image is an ajax form submit. Code:
$("#sub_form").click(function() {
var input_data = $('#testform').serialize();
$.ajax({
//my code
});
});
how can i achieve this after deleting the image.
source to share
If you've saved the handler, you can simply call it again:
var handler = function() {
alert('click');
};
$('#sub_form').click(handler);
// disabling:
$('#sub_form').unbind('click', handler);
// reenabling:
$('#sub_form').click(handler);
If you don't know which handlers are associated, you can find and save them before disconnecting:
// save the click handlers
var events = $('#sub_form').data('events'),
handlers = 'click' in events ? Array.prototype.slice.call(events.click) : [],
handler = function() {
$.each(handlers, function() {
this.handler();
});
};
// disable
$('#sub_form').unbind('click');
// reenable
$('#sub_form').bind('click', handler);
source to share
You need to provide your event handler with a function to run when an event occurs, try this:
$('#sub_form').bind('click', function() {
alert("You clicked #sub_form");
});
If you are going to bind / decouple regularly, it would be better to put the logic in its own function so that it can be bounced easily:
$("#element").click(function() {
$("#sub_form").unbind();
// do something
$("#sub_form").bind('click', myFunc);
});
function myFunc() {
alert("You clicked #sub_form");
}
source to share
You can specify function reference
when calling .unbind()
:
For example:
function myHandler( event ) {
}
// bind the click handler
$('#sub_form').bind('click', myHandler);
// remove only this exact click handler
$('#sub_form').unbind('click', myHandler);
// bind it again
$('#sub_form').bind('click', myHandler);
Sidenote . As of jQuery 1.7.x, you must use the equivalent methods .on()
and .off()
.
source to share