-2

I need to trigger a method when a hover is made on a button for continous 1000 ms. Whenever hover is on other elements then timeout should be reset. How do I implement such thing using javascript/ jquery ?

Preferred solution would be one not requiring use of new plugin.

Rajat Gupta
  • 25,853
  • 63
  • 179
  • 294

1 Answers1

6

Try

$(function(){
    var timer;

    $('.item').hover(function(){
        timer = setTimeout(function(){
            console.log('do it')
        },  1000);
    }, function(){
        clearTimeout(timer);
    });
})

Update:

$(function(){
    $('body').on('mouseenter', '.item', function(e){
        var timer = setTimeout(function(){
            console.log('do it', e.target)
        },  1000);
        $(this).data('myTimer', timer);
    }).on('mouseleave', '.item', function(e){
        clearTimeout($(this).data('myTimer'));
    });
})

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • i use `'hover'` with `.live()` or `.on()` to apply to elements that match selector in future. could you please tell how to modify your solution to use with `.on()` – Rajat Gupta May 08 '13 at 12:30
  • `hover` is not an event, you need to use `mouseenter` and `mouseleave` – Arun P Johny May 08 '13 at 12:36