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();
});
CodePudding user response:
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');
});
CodePudding user response:
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); });