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.
The onmouseover event occurs when the mouse pointer is moved onto an element, or onto one of its children. Tip: This event is often used together with the onmouseout event, which occurs when a user moves the mouse pointer out of an element.
The hover() method specifies two functions to run when the mouse pointer hovers over the selected elements. This method triggers both the mouseenter and mouseleave events. Note: If only one function is specified, it will be run for both the mouseenter and mouseleave events.
The onmouseout event occurs when the mouse pointer is moved out of an element, or out of one of its children. Tip: This event is often used together with the onmouseover event, which occurs when the pointer is moved onto an element, or onto one of its children.
You can simply use the CSS :hover pseudo-class selector in combination with the jQuery mousemove() to check whether the mouse is over an element or not in jQuery.
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 ( 'undefined' != typeof obj.addEventListener ) { obj.addEventListener( evt, fn, false ); } else if ( 'undefined' != typeof obj.attachEvent ) { 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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With