Interesting one for me. I've got a video player whos controls are showed on hover. Initially, I did this with CSS but had to change strategy to javascript to play nice with browsers fullscreen api (which, incidentally means you're always hovering on the video).
My new approach is setting an event handler for mousemove for the video's container that adds a class and sets a timeout to remove it, and if the timeout is already set, clears it. This works perfectly, but the logic doesn't scale to more than one player.
TLDR: how can I expand my logic to scale to more than one video container? The scope of the time variable needs to be contained to each elements event, but also outside of the handler so that it can be cleared out from one event to the next (on the same element).
Thanks for your help- these logic questions are always difficult for me.
Here's a jsFiddle example. You'll notice that it works well when you limit hovering to one element, but there are issues when you expand to the rest of the elements on the page.
HTML:
<div class="cont">
<div class="controls">controls</div>
</div>
JavaScript:
var time;
$('body').on('mousemove', '.cont', function(){
var thiis = $(this);
if (time){
clearTimeout(time);
}
thiis.addClass('showControls');
time = setTimeout(function(){
thiis.removeClass('showControls');
}, 2000);
});
You could store the time variable using jQuery's data method which can store data on each of your elements.
$('body').on('mousemove', '.cont', function(){
var thiis = $(this),
// get the time from the data method
time = thiis.data("timer-id");
if (time){
clearTimeout(time);
}
thiis.addClass('showControls');
var new_time = setTimeout(function(){
thiis.removeClass('showControls');
}, 2000);
// save the new time
thiis.data("timer-id", new_time);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With