Remove Event Listener From Window Object Using Jquery
Solution 1:
You can't do it your way.
jQuery can only unbind all event handlers for a given event if the original listeners were configured using jQuery.
This is because an event that is added with addEventListener()
must be removed with removeEventListener()
and removeEventListener()
requires a second argument that specifies the callback function.
From the MDN page:
target.removeEventListener(type, listener[, useCapture])
If the event is originally registered using jQuery, jQuery works around this by having only one master event registered with addEventListener that points to it's own callback function and then using it's own event dispatching to all the events registered via jQuery. This allows it to support generic .unbind()
like you're trying to use, but it will only work if the original event is registered with jQuery and thus goes through the jQuery event handler management system.
So, without jQuery, you would do it like this:
functionblurHandler() {
document.title = "Blurred" ;
}
functionfocusHandler() {
document.title = "In Focus" ;
}
functionaddEvents(){
window.addEventListener('blur', blurHandler);
window.addEventListener('focus', focusHandler);
}
functionremoveWinowEvents() {
window.removeEventListener('blur', blurHandler);
window.removeEventListener('focus', focusHandler);
}
With jQuery, you could do it like this:
functionaddEvents(){
$(window).on('blur', function(){ document.title = "Blurred" ; })
.on('focus', function(){ document.title = "In Focus" ;});
}
functionremoveWindowEvents() {
$(window).off('blur focus');
}
Solution 2:
try binding with jquery see Using JQuery to bind "focus" and "blur" functions for "window", doesn't work in IE
$(function() {
$(window).focus(function() {
console.log('Focus');
});
$(window).blur(function() {
console.log('Blur');
});
});
Post a Comment for "Remove Event Listener From Window Object Using Jquery"