Remove keydown event from jquery element not working
As the .click() method is just a shorthand for .on( "click", handler ), detaching is possible using .off( "click" ):
$("#element").off("click", function(){
$("#element").hide(); //not working
});
$("#element2").on("click", function() {
$("#element2").hide(); //working
});
So if you have a .keydown( handler ), it is a shortcut for .on( "keydown", handler ) in the first and second variations, and .trigger( "keydown" ) in the third.
The arguments provided must match for the event handler to be removed.
If you do not want to touch the existing script or it may be changed i recommend you simply include an external .js script to the html page to unbound the events:
<script src="your_external_script.js"></script>
with similar content:
$(document).ready(function(){
$("#element2").unbind("click");
});
.off( events [, selector ] [, handler ] ): version added: 1.7
.unbind( eventType [, handler ] ): version added: 1.0
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()
So, I suggest to pay attention to the jQuery version, because bind/unbind are not used so much more.
In the following snippet you can see the .off() works fine:
$( window ).load(function() {
$("#element").keydown(function(e) {
console.log('keydown event');
});
$("#elementOff").click(function() {
// unbind keydown
$("#element").off('keydown');
// attach click
$("#element").off('click').click(function(e) {
console.log('click event');
});
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<form>
<input id="element" type="text">
</form>
<button id="elementOff">Unbind Keydown and attach Click</button>