12

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?

Freexel
  • 123
  • 1
  • 1
  • 5
  • 3
    Instead, use [addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener) in IE 9,10,11 – Givi Nov 24 '13 at 19:46
  • 3
    possible duplicate of [addEventListener in internet explorer](http://stackoverflow.com/questions/6927637/addeventlistener-in-internet-explorer) – MartyIX Nov 24 '13 at 19:56

1 Answers1

16

.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().

Community
  • 1
  • 1
ajp15243
  • 7,704
  • 1
  • 32
  • 38
  • 1
    Anyone that reads this later should be aware typeof window.attachEvent comes back with 'object' vs 'function'. – Mark Sep 08 '15 at 17:20
  • 3
    @Mark A fun quirk of older IEs, they don't return `"function"` for `typeof` on functions, instead returning `"object"`. They're not exactly wrong, but it isn't nearly as helpful. I've changed my answer's conditional checks to simply check for existence instead of inspecting the type, since that will be good enough for pretty much anyone. – ajp15243 Sep 09 '15 at 01:39
  • I'd rather call it `eventName` over `eventType`. See https://developer.mozilla.org/en-US/docs/Web/Events – Volker E. Feb 17 '16 at 20:09