How to create a HTML5 background video using HTML, CSS and JavaScript

programming-ide

https://html5backgroundvideos.com/how-to-create-a-html5-background-video-using-html-css-and-javascript/

 

HTML – remove the poster attribute and add a class telling it to fade in:

 
<video class="fade-in-video" autoplay loop muted>

CSS – add the poster as a background image instead, and styles for the opacity classes:

.video-bg {
    ...
    background: url(path/to/poster.jpg) center center no-repeat;
    background-size: cover; /* Should be run through an auto-prefixer */
}
.fade-in-video {
    opacity: 0;
    transition: opacity .8s linear;
}
.fade-in-video.is-playing {
    opacity: 1;  
}

JavaScript – add the .is-playing class when the video starts:

var fade_in_videos = document.querySelectorAll('.fade-in-video');
for( i=0; i<fade_in_videos.length; i++ ) {
    fade_in_videos[i].addEventListener("playing", function(){
        this.className += ' is-playing';
    });
}

This JavaScript allows for multiple background videos on your page, and should be placed after all your video tags, or if you’re using jQuery, inside $(document).ready().

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.