I'm trying to get the "onmouseout" function on a delay. So that when you move the mouse the video returns to the poster after a few seconds. The following code instantly returns you to the poster onmouseout.
<video class="content"
poster="/video/test.jpg"
width="320"
height="240"
loop onmouseover="this.play()"
onmouseout="this.load();" >
<source src="/video/test.mp4" type="video/mp4">
</video>
The following code is a working example I can get something to work after a delay of onmouseout:
<video class="content"
poster="/video/test.jpg"
width="320"
height="240"
loop onmouseover="this.play()"
onmouseout="myFunction();" >
<script>
function myFunction() {
setTimeout(function(){ alert("Hello"); }, 3000);
}
</script>
<source src="/video/test.mp4" type="video/mp4">
</video>
How do i get "this.load" in setTimeout?
setTimeout accepts a function as its first parameter so you can pass this.load
as the first parameter and use it in the onmouseout attribute as such:
<video class="content"
poster="/video/test.jpg"
width="320"
height="240"
loop
onmouseover="this.play()"
onmouseout="setTimeout(this.load.bind(this), 3000)" >
<source src="/video/test.mp4" type="video/mp4">
</video>
edit: I had a bug (sorry) I'm now using bind function to bind the video element to the load
function.
However it's not the best way to do it because if you use the onmouseout
property or any other HTML property that attach events, you can only attach one onmouseout
event. In most cases you would want to attach more than one. So a better solution would be using the addEventListener
method:
HTML:
<video id="content-video"
class="content"
poster="/video/test.jpg"
width="320"
height="240" >
<source src="/video/test.mp4" type="video/mp4">
</video>
JS:
const video = document.getElementById("content-video");
video.addEventListener("mouseover", function() {
video.play();
}, false);
video.addEventListener("mouseout", function() {
setTimeout(video.load.bind(video), 3000);
}, false);
edit: I'm really sorry about the bugs. I fixed them and it's working now.