onmouseover doesn't work when using javascript to add img tag on IE

Mike W picture Mike W · Nov 12, 2009 · Viewed 16.2k times · Source

I need some javascript code that dynamically adds an img tag to a div, and the img tag needs onmouseover and onmouseout handlers.

I have it working on Firefox. But it doesn't quite work on IE. On IE, the img tag is added, but the onmouseover and onmouseout handlers are not active.

Here's the code:

<body>  
    <div id='putImageHere' />  

    <script type='text/javascript'>
        var node = document.getElementById('putImageHere');
        var img = document.createElement('img');
        img.setAttribute('src', 'http://sstatic.net/so/img/logo.png');
        node.appendChild(img);

        // first attempt, which works on Firefox but not IE
        img.setAttribute('onmouseover', "alert('mouseover')");
        img.setAttribute('onmouseout', "alert('mouseout')");

        // second attempt, which I thought would work on IE but doesn't
        img.addEventListener('mouseover', function() { alert('mouseover') }, false);
        img.addEventListener('mouseout', function() { alert('mouseout') }, false);
    </script>  
</body>  

Answer

Omer Bokhari picture Omer Bokhari · Nov 12, 2009
if (img.addEventListener) {
    img.addEventListener('mouseover', function() {}, false);
    img.addEventListener('mouseout', function() {}, false);
} else { // IE
    img.attachEvent('onmouseover', function() {});
    img.attachEvent('onmouseout', function() {});
}

look into using one of the many popular javascript libraries (jquery, prototype, etc). they hide browser inconsistencies so you don't need to worry about writing code like above.