Question

I have some javascript code that creates an img tag with a mouseover callback, and adds the img tag to the page. The problem is that a javascript syntax error happens (in the Firefox Console) whenever the callback is invoked.

This code demonstrates the problem...

    
        var imgUrl = 'http://sstatic.net/so/img/logo.png';
        var img = document.createElement('img');
        img.setAttribute('src', imgUrl);
        img.setAttribute('onmouseover', function() {
            alert('mouseover ' + imgUrl);
        });
        document.body.appendChild(img);
    

The syntax error even happens when the callback function is an empty function.

Can anyone explain what's causing the syntax error and how to fix it?

(I'm using FF 3.5.2 on Win XP.)

Was it helpful?

Solution

You're passing in a function where a string is expected. Try this instead:

    var imgUrl = 'http://sstatic.net/so/img/logo.png';
    var img = document.createElement('img');
    img.src = imgUrl;
    img.onmouseover = function() {
        alert('mouseover ' + imgUrl);
    };
    document.body.appendChild(img);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top