views:

9869

answers:

4

Is there a canonical way to set up a JS onHover event with the existing onmouseover, onmouseout and some kind of timers? Or just any method to fire an arbitrary function if and only if user has hovered over element for certain amount of time.

+1  A: 

Can you clarify your question? What is "ohHover" in this case and how does it correspond to a delay in hover time?

That said, I think what you probably want is...

var timeout;
element.onmouseover = function(e) {
    timeout = setTimeout(function() {
        // ...
    }, delayTimeMs)
};
element.onmouseout = function(e) {
    if(timeout) {
        clearTimeout(timeout);
    }
};

Or addEventListener/attachEvent or your favorite library's event abstraction method.

eyelidlessness
A: 

I don't think you need/want the timeout.

onhover (hover) would be defined as the time period while "over" something. IMHO

onmouseover = start...

onmouseout = ...end

For the record I've done some stuff with this to "fake" the hover event in IE6. It was rather expensive and in the end I ditched it in favor of performance.

scunliffe
+4  A: 

How about something like this?

<html>
<head>
<script type="text/javascript">

var HoverListener = {
    addElem: function( elem, callback, delay )
    {
     if ( delay === undefined )
     {
      delay = 1000;
     }
     var hoverTimer;
     addEvent( elem, 'mouseover', function()
     {
      hoverTimer = setTimeout( callback, delay );
     } );
     addEvent( elem, 'mouseout', function()
     {
      clearTimeout( hoverTimer );
     } );
    }
}

function tester()
{
    alert( 'hi' );
}

//  Generic event abstractor
function addEvent( obj, evt, fn )
{
    if ( typeof obj.addEventListener != undefined )
    {
     obj.addEventListener( evt, fn, false );
    }
    else if ( typeof obj.attachEvent != undefined )
    {
     obj.attachEvent( "on" + evt, fn );
    }
}

addEvent( window, 'load', function()
{
    HoverListener.addElem( document.getElementById( 'test' ), tester );
    HoverListener.addElem( document.getElementById( 'test2' ), function(){ alert( 'Hello World!' ); }, 2300 );
} );

</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>
Peter Bailey
+2  A: 

If you use the JQuery library you can use the .hover() event which merges the mouseover and mouseout event and helps you with the timing and child elements:

$(this).hover(function(){},function(){});

The first function is the start of the hover and the next is the end. Read more at: http://docs.jquery.com/Events/hover

MikeN