Sir
Sir

Reputation: 8280

Conflicting functions running at same time from event listener

I have a piece of javascript code which listens for mouse over's and makes a div fade out and back in.

The problem i have is if the user mouse overs multiple times thus causing the logic of the function to do this:

mouse over¬
   fade out
   fade in [mouse over again] ¬  
                     fade out

At which point i have both a fade out and a fade in occurring at the same time causing a weird flickering on the div. And I am not sure how to prevent it.

Working fiddle: http://jsfiddle.net/WgNuX/4/ move the mouse in an out of the div very quickly and it will flicker.

My code is as follows:

function check(){
    var div_id = document.getElementById('my_div');
    var opacity = window.getComputedStyle(div_id).opacity;

    function fade_in(){
        var opacity = window.getComputedStyle(div_id).opacity;
        var direction =1 ; //fade in

        transition_opacity(div_id,opacity,direction,0)
    }


    var direction = 0; //fade out first
    transition_opacity(div_id,opacity,direction,fade_in)

}

 var div_id = document.getElementById('my_div');
 div_id.addEventListener('mouseover',check,false);

What can i do to prevent this from occuring ?

Upvotes: 4

Views: 347

Answers (2)

Travis J
Travis J

Reputation: 82287

jsFiddle Demo

You should probably just use a flag to control the motion.

var busy = false;
function check(){
 if( busy ) return;
 busy = true;
 ...
function fade_in(){
 var opacity = window.getComputedStyle(div_id).opacity;
 var direction =1 ; //fade in  
 transition_opacity(div_id,opacity,direction,function(){busy=false;});
}

This will prevent the animation from starting until it has completed.

Upvotes: 1

JCleveland
JCleveland

Reputation: 337

Store the state of the fade in in a global variable/hidden input field. 1 when it starts, zero when it stops. Don't run fade out if the variable is 1.

Upvotes: 0

Related Questions