Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only execute function if mouse has hovered for more than 1 second

Tags:

jquery

I would like to add and remove classes on elements when a user hovers over an element, but only if their cursor has been on it for more than 1 second for example. How can I achieve this?

$("#thumbs div").mouseenter(function() {
    $('#thumbs div').removeClass('hovered');
    $(this).addClass('hovered');
});
like image 945
user1937021 Avatar asked Sep 23 '13 17:09

user1937021


People also ask

What is difference between Mouseenter () and mouseover () event?

The mouseover event triggers when the mouse pointer enters the div element, and its child elements. The mouseenter event is only triggered when the mouse pointer enters the div element.

What is the function of mouse hover?

In computing, a mouseover , mouse hover or hover box is a graphical control element that is activated when the user moves or hovers the pointer over a trigger area, usually with a mouse, but also possible with a digital pen. Mouseover control elements are common in web browsers.

What is mouse hover event?

The mouseover event is fired at an Element when a pointing device (such as a mouse or trackpad) is used to move the cursor onto the element or one of its child elements.


1 Answers

Use a timer:

var timer;
$("#thumbs div").mouseenter(function() {
    var that = this;
    timer = setTimeout(function(){
        $('#thumbs div').removeClass('hovered');
        $(that).addClass('hovered');
    }, 1000);
}).mouseleave(function() {
    clearTimeout(timer);
});

http://jsfiddle.net/qGRcH/

like image 58
bfavaretto Avatar answered Oct 24 '22 06:10

bfavaretto