1

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.)

1
  • Can you update your question and put in the error you get? Commented Sep 9, 2009 at 19:58

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

3 Comments

it works, but I'm still not exactly sure why, what did you change?
The function was assigned directly to the method, not via the setAttribute function, where a string is expected. A much cleaner solution than mine. +1
@CrazyJugglerDrummer: the setAttribute method takes 2 strings - so you could've used that method but you would have had to wrap the function in double-quotes and this could also have caused problems accessing the imgUrl value as now it would be looked for in global scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.