3

im new to most web dev stuff so im kindly asking you for some support. i have an image map in which i have assigned several areas triggering different contents in a separate div. i would now like to add a delay to the onmouseover trigger so that the content in the div is only updated if the user positions the curser on the area instead of accidentally hovering over it.

this is the js i use for toggling the div contents:

function showHideDivs(indx){
hideDivs();
oShowHideDivs[indx].style.display = 'block';
}

function hideDivs(){
for(i=0; i < oShowHideDivs.length; i++){
    oShowHideDivs[i].style.display = 'none';
}
}

window.onload=function(){
oShowHideDivs = document.getElementById('container').getElementsByTagName('div');
var oMap = document.getElementById('myMap');
for(i=0; i < oMap.areas.length; i++){
    oMap.areas[i].indx = i;
    oMap.areas[i].onmouseover=function(){
        showHideDivs(this.indx);
    }
  }
}

so how do i implement the delay and where? thx in advance! jan

EDIT: i used this approach now:

oMap.areas[i].onmouseover=function(){
var area=this;
var delay=setTimeout(function(){showHideDivs(area.indx);},100);
area.onmouseout=function(){clearTimeout(delay);};
}

seemed the easiest to me. thx for the hint!

user1524098
  • 61
  • 1
  • 6
  • Would you be open to using jQuery? Check out [this question](http://stackoverflow.com/questions/10933828/a-function-to-check-if-the-mouse-is-still-hovering-an-element-every-10-milliseco) and [this jsfiddle](http://jsfiddle.net/z8yaB/). – rosshamish Dec 02 '12 at 19:30

2 Answers2

4

The easiest way is to include a timeout on mouseover, and clear it on mouseout.

oMap.areas[i].onmouseover=function(){
    var area=this;
    var delay=setTimeout(function(){showHideDivs(area.indx);},100);
    area.onmouseout=function(){clearTimeout(delay);};
}

For more complex scenarios, use a plugin like hoverintent.

Christophe
  • 27,383
  • 28
  • 97
  • 140
0

You need to use setTimeout() to call your function showHideDivs() after a certain delay. And you stop this function from being called if the user moves its mouse before the end of your delay.

Look here for a concrete example : https://stackoverflow.com/a/6231142/1606729

Community
  • 1
  • 1
koopajah
  • 23,792
  • 9
  • 78
  • 104