Have a look at the following page and before clicking anywhere in it, hover over the video and check your console - an error is thrown and the video doesn't play...
https://codepen.io/gil--/pen/bNxZWg
Jquery code:
var figure = $(".video").hover( hoverVideo, hideVideo );
function hoverVideo(e) {
$('video', this).get(0).play();
}
function hideVideo(e) {
$('video', this).get(0).pause();
}
ERROR: Uncaught (in promise) DOMException
However, when you click somewhere on the page and then hover the video, it plays and no errors are thrown. I'm using the same code on my site hence, I'd like to fix it. This is super strange!
The reason for the error is because there is a new "rule", since 2016, about triggering a video play in most "modern" browsers. See this Google's dev blog post. It now requires the user to "interact" with the page at least once before the programatical trigger.
So I suggest you to fing a way to have the user at least click somewere in your webpage... Be it a nearly useless button and a flag to make sure to prevent the error.
Have a look below. Also on CodePen
I'm sure you can have that button (or any click invitation) cuter ;)
var figure = $(".video").hover( hoverVideo, hideVideo );
function hoverVideo(e) {
if(playEnabled){
$('video', this).get(0).play();
}
}
function hideVideo(e) {
if(playEnabled){
$('video', this).get(0).pause();
}
}
var playEnabled = false;
$("#enablePlay").on("click",function(){
playEnabled = true;
$(this).html("Video play enabled!");
});
#videosList {
max-width: 600px;
overflow: hidden;
}
.video {
background-image: url('https://img.youtube.com/vi/nZcejtAwxz4/maxresdefault.jpg');
height: 330px;
width: 600px;
margin-bottom: 50px;
}
/* Hide Play button + controls on iOS */
video::-webkit-media-controls {
display:none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--
Data: https://gfycat.com/cajax/get/VerifiableTerrificHind
Source: https://www.youtube.com/watch?v=nZcejtAwxz4
More info on youtube api for thumbnails: http://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
-->
<div id="videosList">
<div class="video">
<video class="thevideo" loop preload="none">
<source src="https://giant.gfycat.com/VerifiableTerrificHind.mp4" type="video/mp4">
<source src="https://giant.gfycat.com/VerifiableTerrificHind.webm" type="video/webm">
Your browser does not support the video tag.
</video>
</div>
Hover mouse over video. Desktop only [ Obviously! ;) ]
</div>
<button id="enablePlay">Click here to play the video on mouse over</button>