Search code examples
javascriptjquerymouseeventmouseover

Mouseover for 1 second before triggering the event


I've written a simple bit of code that shows a div on a mouseover event. I'd like to mouseover the element for 1s before the event takes place. Any ideas on how I can achieve this? with a brief explanation if possible so I know for next time.

$('.NavSelect h2').mouseover(function() {
$('.NavGroup').hide();
$('#' + $(this).prop('id').replace('item','content')).show();
});

Solution

  • If I understand what you want to do, you need a setTimeout:

    $('.NavSelect h2').mouseover(function() {
      setTimeout(() => {
        $('.NavGroup').hide();
        $('#' + $(this).prop('id').replace('item','content')).show();
      }, 1000);
    });
    

    Here, the documentation

    Update

    If you would clear the timeout on mouseleave I suggest you somethig like this:

    let time = 0;
    $('.NavSelect h2').mouseover(function() {
      time = setTimeout(() => {
        $('.NavGroup').hide();
        $('#' + $(this).prop('id').replace('item','content')).show();
      }, 1000);
    }).mouseleave(() => { clearTimeout(time); });