How to change Javascript to work with IE
Can someone please tell me how to fix the code below so that it works with IE. It currently works with Chrome and Firefox. Thanks.
<style type="text/css">
.highlight{
background-color: orange;
color: white;
}
</style>
<script type="text/javascript">
function createListener(){
document.addEventListener('click', function(event){
var element=event.target;
if(element!==document.body){
if(element.className===''){
element.className='highlight';
} else {
element.className='';
}
}
}, false);
}
</script>
<body onload="createListener()">
Re: How to change Javascript to work with IE
You could debug the scripts, in IE using F12. Then you can see where the problem is and you can google that or ask here again.
Re: How to change Javascript to work with IE
The code should work in Internet Explorer versions 9+. In earlier versions the non-standard 'attachEvent' method must be used instead of 'addEventListener'.
Also, I recommend attaching all event listeners using JavaScript instead of HTML attributes. This keeps behaviour and presentation as separate as possible.
With those things in mind, here is how I would restructure the code:
Code:
function listen(who, event, callback)
{
if (who.addEventListener)
who.addEventListener(event, callback, false);
else if (who.attachEvent)
who.attachEvent('on' + event, callback);
}
function createListener()
{
var handler = function(event) {
var element = event.target;
if (element !== document.body)
{
if (element.className === '')
element.className = 'highlight';
else
element.className = '';
}
};
listen(document, 'click', handler);
}
listen(document, 'ready', createListener);
Untested, so there might be some typos.
Edit: The document.ready listener isn't required in this particular case because you can attach the document.click listener immediately, but I added it as an example of an alternative to your original 'onload' method.