I have some custom html5 video controls and I'd like to hide them when a user is watching the video. I'll wait two seconds and if they're not moving their mouse, I'll hide the controls, then when they move the mouse again I'll show the controls.
What's a practical, performing way to do this?
Use
mousemove
event withsetTimeout
Clear the setTimeout
if mouse
is moving
var elem = document.getElementById('controls'); var timeout; var duration = 3000; document.addEventListener('mousemove', function() { elem.textContent = 'Mouse is moving!' clearTimeout(timeout); timeout = setTimeout(function() { elem.textContent = 'Mouse Has stopped!' }, duration) });
<div id="controls">Mouse Has stopped!</div>
Implementation using controls
attribute
var video = document.getElementById('videoElem'); var timeout; var duration = 500; document.addEventListener('mousemove', function() { video.setAttribute("controls", "controls"); clearTimeout(timeout); timeout = setTimeout(function() { video.removeAttribute("controls"); }, duration) });
html { padding: 20px 0; background-color: #efefef; } body { width: 400px; padding: 40px; margin: 0 auto; background: #fff; box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.5); } video { width: 400px; display: block; }
<video preload controls id="videoElem"> <source id="mp4" src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4"> </video>
I ended up using the timeupdate event:
var counts = 0
function hideOnIdle (video) {
if (video.paused === true) return controls.classList.remove('hidden')
if (counts > 7) {
controls.classList.add('hidden')
counts = 0
}
counts += 1
}
document.addEventListener('mousemove', function (event) {
controls.classList.remove('hidden')
counts = 0
}, false)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.