0

Possible Duplicate:
JavaScript: remove event listener

I am attempting to remove some event listeners from a navigation, after a start button is clicked. I can't seem to get anything to fire.

Here is the code I'm using to do it:

var startButton = document.getElementById('startButton');

startButton.addEventListener('click', function() {
    hrNav.removeEventListener('mousedown', highlight, false);
    alert('Did it remove the listener?');
}, false); 

The eventlistener that I'm trying to remove is:

if(hrNav.addEventListener){  
    hrNav.addEventListener('mousedown', highlight, false);  
    return true;  
} else {  
    hrNav.attachEvent('on'+'click', highlight);  
    return true;  
}

All of it is wrapped in a jQuery document.ready function.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
mdance
  • 966
  • 5
  • 16
  • 36

1 Answers1

0

Since you said you're using jQuery. Try something like this: http://jsfiddle.net/MmFb2/4/

JS

$(function(){
    var startButton = $('#startButton');
    var hrNav = $('#hrNav');

    startButton.bind('click', function() {
        hrNav.unbind('click');
    }); 

    var toggle = false; 
    hrNav.bind('click', function(){
        var ele = $(this); 
        if(toggle){
            ele.css('background-color', '');
        }else{            
            ele.css('background-color', 'yellow');
        }
        toggle = !toggle;
    });
}); 

HTML

<input id="startButton" type="button" value='click to disable' />
<div id="hrNav">Click me to highlight</div>​
Brandon Boone
  • 16,281
  • 4
  • 73
  • 100
  • Is "unbind" the same thing as removing the event listener I previously set? – mdance Sep 18 '12 at 00:20
  • Yes, it's jQuery's abstraction of that action. Instead of having to account for all the idiosyncrasies specific to a particular browser. jQuery creates a single point of entry to abstract away all those differences allowing the developer to focus on the task at hand and not how to accomplish it in IE6-10, Firefox, Chrome, Opera, Safari, etc. This is not only true with event binding/unbinding, but also with DOM manipulation and DOM element retrieval. Well worth your investment in my opinion. – Brandon Boone Sep 18 '12 at 01:16