Search code examples
javascriptintervalsonmouseoveronmouseout

onmouseover and onmouseout functions containing intervals not executing correctly


I am doing some experimentation with JavaScript and I have a list of 4 items displayed horizontally, with each list item having an onmouseover and onmouseout event assigned.

The onmouseover event for each item executes a function which increases the height of the item over time using an interval.

the outmouseover event for each item executes a function which then reduces the height of the item to its default value over time using another interval.

It is working in the following scenario: When I trigger the onmouseover for a list item the height increases as expected, and when I take the mouse off the list item the height then decreases as expected.

The problem is however, it doesn't seem to work in the following scenario: When I trigger the onmouseover for a list item the height increases as expected, however if I trigger another onmouseover event for another list item before the item has returned to its original size, the onmouseout function for the previous list item does not finish executing.

Sorry if I am lacking any detail, evidently I am incredibly bad at explaining things.... So I have a link to the source code and a site where you can test the code to see what is happening.

Maybe I do not have as much of a knowledge of javascript as I thought, so while a solution or fix would be amazing, I am also happy to accept any advice or some kind of explanation as to why this could be happening.

I thought initially that multiple interval timers could not execute simultaneously, until after some research I found they can. So now I am thinking if it is a conflict between the onmouseover and onmouseout events.

Any advice, guidance or a solution would be extremely appreciated!


Source: https://docs.google.com/open?id=0B6XLOOGyKVdWVkpSUklmMVI5QUk
Testing Site: http://www.play-hookey.com/htmltest/
(just copy the contents of that google document and paste into the html text area in the site to see what I am talking about)


Solution

  • Your code:

    icon.onmouseover = function(){ enlarge(this, icon.ID); };
    icon.onmouseout = function(){ reduce(this, icon.ID); };
    

    Correct code:

    icon.onmouseover = function(){ enlarge(this, this.ID); };
    icon.onmouseout = function(){ reduce(this, this.ID); };
    

    What happened: you bindded an event with a function and passed variables to it. After each for loop, you redefined that function variable (so at the end, your icon.ID=3). That means that all on event called functions where using same icon.ID=3.

    I hope that make sense...