Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove event listener from window object using jquery

I am trying to remove blur and focus event listeners from window object using jquery's unbind function using:

function removeWindowEvents(){
    $(window).unbind('blur') ; 
    $(window).unbind('focus') ;
}

I registered the event using Javascript:

function addEvents(){
window.addEventListener('blur', function(){ document.title = "Blurred" ; });
window.addEventListener('focus', function(){ document.title = "In Focus" ;}); 


}

This however does not work. What am I doing wrong? I tested this is Mozilaa and Chrome(latest versions)

like image 214
Varun Jain Avatar asked Sep 22 '13 19:09

Varun Jain


1 Answers

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:

function blurHandler() {
    document.title = "Blurred" ;
}

function focusHandler() {
    document.title = "In Focus" ;
}

function addEvents(){
    window.addEventListener('blur', blurHandler);
    window.addEventListener('focus', focusHandler); 
}

function removeWinowEvents() {
    window.removeEventListener('blur', blurHandler);
    window.removeEventListener('focus', focusHandler);
}

With jQuery, you could do it like this:

function addEvents(){
    $(window).on('blur', function(){ document.title = "Blurred" ; })
             .on('focus', function(){ document.title = "In Focus" ;}); 
}

function removeWindowEvents() {
    $(window).off('blur focus');
}
like image 87
jfriend00 Avatar answered Sep 18 '22 02:09

jfriend00