function createimg() { var...">

Assign an onmouseover event handler

Please tell me what is wrong with this code:

 <script type="text/javascript" >

function createimg()
       {
         var img = new Image();
       img.src='link/to/image';
       img.alt='Next image';  img.id = 'span1'; img.style.zIndex = 10;
       img.style.position = 'absolute';  img.style.display='block'; img.style.top = '130px';
       img.style.padding='10px'; img.style.left='440px';    img.className ='dynamicSpan';
        document.body.appendChild(img);
        return img;
        }

    function al()
    {
     alert('loaded');
    }
   a = createimg();

    a.onmouseover = al();

</script>

      

Specifically the last part where I am trying to assign an onmouseover event handler for a which is an image element. For some reason, it doesn't assign this event handler and just does the page load function.

What's wrong?

Tony

+2


source to share


5 answers


a.onmouseover = al;

      



When you write al()

, you call the function in place and assign the return value of the function (which is undefined since there is no instruction return

) to a.onmouseover

. You want to assign this function instead, so you just need to remove the parentheses.

+13


source


Well, for starters, your code is not formatted to be easy to read.

But your problem is here:

a.onmouseover = al();

      

What do you really want:



a.onmouseover = al;

      

The operator ()

calls the function. Thus, the expression al()

is equal to the result of the function execution al

- this means that the function al

must be executed before its result (which in this case is equal undefined

) can be assigned a.onmouseover

.

In contrast, if you just use al

, the expression equals the function object al

that you actually want to assign to the event. In this case, when the event is triggered, the function is executed al

.

+2


source


Try

a.onmouseover = al;

      

instead

a.onmouseover = al();

      

0


source


    a.onmouseover = al;

      

0


source


Replace:

a.onmouseover = al ();

FROM

a.onmouseover = al;

      

0


source







All Articles