Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attachEvent Doesn't work in IE > 8.0

I'm using attachEvent for a while, but it seems that IE doesn't support this anymore?

window.attachEvent("onload",Start_Wysiwyg);
window.attachEvent("onscroll",ScrollEditBar,false);

Does anyone have a solution for this problem?

like image 759
user3029098 Avatar asked Nov 24 '13 19:11

user3029098


1 Answers

.attachEvent() is deprecated in IE9+, and has been removed in IE11.

The standard is .addEventListener() (MSDN docs). The MDN docs have a section about compatibility.

You can simply run some feature-checking code to check if the supported features exist:

if (window.addEventListener) {
    // Check for addEventListener first, since IE9/10 have both,
    // but you should use the standard over the deprecated IE-specific one
    window.addEventListener('click', myFunc);
} else if (window.attachEvent) {
    window.attachEvent('onclick', myFunc);
}

If you have to attach a lot of event listeners, then you may want to just cache the desired listener attachment method in a variable and use that variable for attaching your events throughout your code, rather than having that above check for every single event listener:

var addListener = function(){}; // Default to no-op function

if (window.addEventListener) {
    addListener = window.addEventListener;
} else if (window.attachEvent) {
    addListener = function(eventType, listener, useCapture) {
        // attachEvent wants 'oneventType' instead of 'eventType'
        window.attachEvent('on'+eventType, listener, useCapture);
    };
}

// Now you can add listeners with a browser-agnostic function call!
addListener('click', myFunc);
addListener('hover', myOtherFunc);

You can read more in a duplicate question linked by @MartyIX in a comment on your question. There are further nuances and methods in the answers/comments there, such as IE9 requiring <!DOCTYPE html> in order to use .addEventListener().

like image 169
ajp15243 Avatar answered Nov 05 '22 15:11

ajp15243