As @NVRM mentioned, "it will be way easier to use a video", taking that advice, I used ezgif to convert the gif to an mp4 video format which made the whole thing a lot easier.
I used the window.onload
function to play the video automatically when it is first opened.
From there, I could use the document.onmouseout
to pause the video when the cursor is out of the body/document and resume the video when the cursor is in the body/docenment with document.onmousemove
. The onmousemove
also allows the video to resume when it's paused from the lack of mouse movement.
To detect no mouse movement, I used this code that uses a setInterval()
function to detect if the mouse hasn't moved in a specific time span, if so, it will execute the code within the function, which in this case, pausing the video.
To clear the no-mouse-detector function when the mouse is out of that window, I used clearInterval()
inside the document.onmouseout
function, otherwise, it keeps thinking the mouse isn't moving when it's not inside the body/document, wasting resources.
const video = document.getElementById("background");
window.onload = function() {
video.play();
};
document.onmouseout = function() {
video.pause()
clearInterval(timeout);
};
document.onmousemove = function() {
video.play();
};
var timeout;
document.onmouseover = function () {
clearInterval(timeout);
timeout = setInterval(function () {
video.pause();
}, 8888);
}
* {
margin: 0;
padding: 0;
overflow: hidden;
}
#background {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: -1000;
transition: 0.2s;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Background Test</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script src="script.js" defer></script>
<video muted loop preload="auto" id="background">
<source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
</video>
</body>
</html>