I still need a vanilla JavaScript solution to attach an event handler in Internet Explorer 8. When I do below code I got an error in IE8 saying:
Object doesn't support property or method 'attachEvent'
How should I fix this?
if ('addEventListener' in document) {
document.addEventListener('DOMContentLoaded', function () {
[].forEach.call(document.querySelectorAll('input'), function (el) {
el.addEventListener('click', function (e) {
e.preventDefault();
alert('nope');
}, false);
});
})
}
else
{
var d = document.getElementsByTagName('input');
d.attachEvent('onclick', function () {
alert('no');
});
}
getElementsByTagName
returns a collection of elements, not a single element. The collection doesn't have attachEvent
. The individual elements do (on older IE).
Note also that:
Your IE-specific branch doesn't wait for the full DOM to be parsed as your standards branch does. Either both should, or both should not, but not a mix. Best practice is not to use DOMContentLoaded
and just put the script at the end of the HTML, immediately prior to the closing </body>
tag.
Your IE event handler isn't preventing the default action, whereas your standards one is.
If you want a cross-browser event attaching function, here's one in another answer on SO.