metaedro
metaedro

Reputation: 33

Overlapping multiple setTimeouts inside jQuery

new here and new to jQuery. I've searched for an answer to my question/ problem without success, so here I come. I'm having problems with this code:

<p>Hello.</p>
<p>Good bye.</p>
<p>Ciao!</p>
<script>
jQuery('p').mouseover(
    function() {
        jQuery(this).css({backgroundColor:'red'});
    }
);
jQuery('p').mouseout(
    function() {
        myElement = jQuery(this);
        setTimeout(function(){
            color = ['red','green','blue','orange'];
            myElement.css({backgroundColor:color[Math.round(Math.random()*3)]});
        }, 1000
        )
    }
);
</script>

The thing is that if we move the cursor over a new paragraph before the last setTimeout function has been executed, then both the first and the second setTimeout functions will act upon the last affected paragraph. For example:

a) Move the cursor over/out a paragraph. Before the setTimeout function associated with the mouseout event is executed,

b) move the cursor over/out a different paragraph. Now the setTimeout function

myElement.css({backgroundColor:color[Math.round(Math.random()*3)]});

will select TWICE consecutively a background color for the second paragraph, and none for the first one. I've tried to associate two different vars (myElementOne and myElementTwo) with the jQuery(this) value to no avail. I would appreciate greatly some help. Thanks.

Upvotes: 3

Views: 156

Answers (2)

Tina CG Hoehr
Tina CG Hoehr

Reputation: 6779

The way I see it, myElement becomes global and only refers to one div at any time. Add var in front of it to make it refer to the particular this in time.

jQuery('p').mouseout(
    function() {
        var myElement = jQuery(this);
        ...

Demo

Upvotes: 0

dvir
dvir

Reputation: 5115

The problem is that your myElement variable is defined in the global scope, and each mouseout execution overwrites the previous value of it.

If you defined myElement with var myElement = jQuery(this);, myElement will be defined only in the scope of the current mouseout event - and will affect only that element in the timeout callback.

Upvotes: 1

Related Questions