1

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();
});
  • As an aside to the question, I'd suggest replacing the ugly `$('#' + $(this).prop('id').replace('item','content'))` logic with a DOM traversal method, such as `find()` - if possible. – Rory McCrossan Dec 14 '21 at 12:44
  • Relevant, for the difference between the two (current) answers: [what is the difference between mouseover and mouseenter](https://stackoverflow.com/questions/1104344/what-is-the-difference-between-the-mouseover-and-mouseenter-events) – freedomn-m Dec 14 '21 at 14:10
  • Hey Rory, do you have any advice or reference information so I can look into making this more efficient =) – Anthony Whitefield Dec 14 '21 at 17:45

2 Answers2

2

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); });
th3g3ntl3man
  • 1,926
  • 5
  • 29
  • 50
2

It's probably best to keep this timeout in a data property and clear it on mouseout.

$('.NavSelect h2').mouseenter(function () {
    $(this).data('timeout', setTimeout(function () {
      $('.NavGroup').hide();
      $('#' + $(this).prop('id').replace('item','content')).show();
    }, 1000));
}).mouseleave(function () {
    clearTimeout($(this).data('timeout'));
    alert('mouse left');
});
freedomn-m
  • 27,664
  • 8
  • 35
  • 57