How to disable event in IE 6 7 8 9 using JavaScript

This is incomplete code, not the full version.

I have a marker that highlights a specific html element when mouse hovers .

I also have click event and listener .

My problem: highlighter event/listener does not disconnect when using Internet Explorer v6 v7 v8 v9

What am I doing wrong?

this is how i attach the event and fire the event listener:

 if (document.body.addEventListener) { //alert(11); document.body.addEventListener('mousemove', handler, false); } else if (document.body.attachEvent) { //alert(12); var ff=function(e) { return handler(e || window.event); }; //alert(ff); document.body.attachEvent('onmousemove', ff); } else { //alert(13); document.body.onmousemove = handler; } 

here is how i can stop the onmousemove / mouse event / listener:

 if (document.body.removeEventListener) { document.body.removeEventListener('mousemove', handler, false); } else if (document.body.detachEvent) { document.body.detachEvent('onmousemove', function(e) { return handler(e || window.event); }); } else { document.body.removeAttribute("onmousemove"); } 

here is how i can stop the onclick / click event / listener:

 if (document.body.removeEventListener) { document.body.removeEventListener('click', ClosetAffairHighlighter.highlightClick, false); } else if (document.body.detachEvent) { document.body.detachEvent('onclick', ClosetAffairHighlighter.highlightClick); } else { document.body.removeAttribute("onclick"); } 
+4
source share
2 answers

base on in this article , a cross-browser event handler could be:

 var EventUtil = { addHandler: function(element, type, handler) { if (element.addEventListener) { element.addEventListener(type, handler, false); } else if (element.attachEvent) { element.attachEvent("on" + type, handler); } else { element["on" + type] = handler; } }, removeHandler: function(element, type, handler) { if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else if (element.detachEvent) { element.detachEvent("on" + type, handler); } else { element["on" + type] = null; } } }; 
+12
source

You need to pass the detachEvent function added using attachEvent . In your code, you pass a new one (they have the same toString() and will do the same, but they do not match).

You have to make ff global with

 var ff; if (document.body.addEventListener) { document.body.addEventListener('mousemove', handler, false); } else if (document.body.attachEvent) { ff=function(e) { return handler(e || window.event); }; 

and then call

 else if (document.body.detachEvent) { document.body.detachEvent('onmousemove', ff); } 

to remove the listener in old IE.

Note. . I really doubt document.body.removeAttribute("onclick"); : is there really a case when this would be useful?

+2
source

Source: https://habr.com/ru/post/1440478/


All Articles