Search code examples
javascripthtmlonmouseout

onmouseout not firing properly


I have this code which is supposed to fire on mouseover and it's counterpart to do the opposite on onmouseout:

colinc();

function colinc(){

    var hexnum=number.toString(16);
    var hexcolor="#"+hexnum+hexnum+hexnum;
    document.getElementById("c"+x).style.backgroundColor=hexcolor;
    number=number+8;
    if(number<=184)
        setTimeout(colinc,50);
}

The counter part only has the change of number = number-8; and number>=40; The problem is i have multiple boxes that should light up with color change on mouseover and lightdown with mouseout. when i move slowly over my boxes(large in no.) then everything is ok but when i move quickly some boxes do not light down...it looks like the onmouseout doesn't happen if i pass very quickly. Any help?

function flash(x){
number=0;
var cc = document.getElementById("c"+x);
var cs=document.defaultView.getComputedStyle(cc,null);
var bg=cs.getPropertyValue('background-color');
var str=""+bg;
var n=str.replace("rgb","");
    n=n.replace("(","");
    n=n.replace(")","");
var arr=n.split(",");
number=parseInt(arr[0]);

colinc();

function colinc(){

    var hexnum=number.toString(16);
    var hexcolor="#"+hexnum+hexnum+hexnum;
    document.getElementById("c"+x).style.backgroundColor=hexcolor;
    number=number+8;
    if(number<=184)
        setTimeout(colinc,50);
}
}

function flashe(x){
number=0;
var cc = document.getElementById("c"+x);
var cs=document.defaultView.getComputedStyle(cc,null);
var bg=cs.getPropertyValue('background-color');
var str=""+bg;
var n=str.replace("rgb","");
    n=n.replace("(","");
    n=n.replace(")","");
var arr=n.split(",");
number=parseInt(arr[0]);

colinc();

function colinc(){

    var hexnum=number.toString(16);
    var hexcolor="#"+hexnum+hexnum+hexnum;
    document.getElementById("c"+x).style.backgroundColor=hexcolor;
    number=number-8;
    if(number>=40)
        setTimeout(colinc,40);
}

}

This is my full js code


Solution

  • Check whether the events fire properly by logging them in the console:

    function MouseOverHandler(event) {
        console.log('mouseover');
    }
    
    function MouseOutHandler(event) {
        console.log('mouseout');
    }
    

    Also do you ever halt the execution of either handlers when the opposite event happens. This would be done via getting the timeout id and canceling it.

    var mouseOverTimeout, mouseOutTimeout;
    
    function colinc(){
        clearTimeout(mouseOutTimeout);
        mouseOverTimeout = setTimeout(colinc,50);
    }
    
    function MouseOutHandler(event) {
        clearTimeout(mouseOverTimeout);
        mouseOutTimeout = setTimeout(MouseOutHandler,50);
    }