Onmouseover doesn't work when using javascript to add img tag in IE

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

I have work on Firefox. But IE is not working. An img tag has been added in IE, but the onmouseover and onmouseout handlers are inactive.

Here is 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>  
+3
source share
4 answers
if (img.addEventListener) {
    img.addEventListener('mouseover', function() {}, false);
    img.addEventListener('mouseout', function() {}, false);
} else { // IE
    img.attachEvent('onmouseover', function() {});
    img.attachEvent('onmouseout', function() {});
}

consider using one of the many popular javascript libraries (jquery, prototype, etc.). they hide browser inconsistencies, so you don’t have to worry about writing code, as shown above.

+6
source
img.setAttribute('src', 'http://sstatic.net/so/img/logo.png');

setAttribute HTMLElement, . Internet Explorer , HTML DOM Level 1:

img.src= 'http://sstatic.net/so/img/logo.png';

setAttribute IE , , , . :

img.setAttribute('onmouseover', "alert('mouseover')");

- , :

img.onmouseover= "alert('mouseover')";

: onmouseover, , , . :

img.onmouseover= function() {
    alert('mouseover');
};

eval, . !

addEventListener, , attachEvent IE ( ). , , onsomething, .

+3

, IE addEventListener. .

, jQuery? , .

0

Ob answer JavaScript ( ), :

onmouseover / out should never be attached as attributes. Basically, you all survived that you are not doing   

just for that in your javascript. Event handler callbacks should always be attached as event listeners via attachEvent for IE, and addEventListener for almost everyone else.

0
source

Source: https://habr.com/ru/post/1722724/


All Articles