Costa Costa - 5 months ago 43
HTML Question

How can I hide my custom html5 video controls when the user is inactive?

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?

Answer

Use mousemove event with setTimeout

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>

Fiddle Demo


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>

Fiddle Demo