MSIE and addEventListener Problem in Javascript?
In IE you have to use attachEvent
rather than the standard addEventListener
.
A common practice is to check if the addEventListener
method is available and use it, otherwise use attachEvent
:
if (el.addEventListener){
el.addEventListener('click', modifyText, false);
} else if (el.attachEvent){
el.attachEvent('onclick', modifyText);
}
You can make a function to do it:
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener){
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent){
el.attachEvent('on'+eventName, eventHandler);
}
}
// ...
bindEvent(document.getElementById('myElement'), 'click', function () {
alert('element clicked');
});
You can run an example of the above code here.
The third argument of addEventListener
is useCapture
; if true, it indicates that the user wishes to initiate event capturing.
In case you are using JQuery 2.x then please add the following in the
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge;" />
</head>
<body>
...
</body>
</html>
This worked for me.