Go to homepage

Projects /

Responsive Video Background

A full-width responsive video background.

View Demo

How to

The Resposive Video Background component can be used to add a full-width background video to a section of your page.

Video background #

If you want to play the background video only when it enters the viewport, and pause when it leaves it, you can include the following JS snippet in your project:

(function() {
  var VideoAutoplay = function(element) {
    this.element = element;
    this.intersectionObserverSupported = ('IntersectionObserver' in window && 'IntersectionObserverEntry' in window && 'intersectionRatio' in window.IntersectionObserverEntry.prototype);
    initVideoAutoplay(this);
  };

  function initVideoAutoplay(video) {
    // use the Intersection Observer API to detect when video enters/leaves the viewport
    video.element.autoplay = video.intersectionObserverSupported ? false : true;
    if(!video.intersectionObserverSupported) return;
    var observer = new IntersectionObserver(videoAutoplayCallback.bind(video));
		observer.observe(video.element);
  };

  function videoAutoplayCallback(entries, observer) {
    entries[0].isIntersecting ? this.element.play() : this.element.pause();
  };

  window.VideoAutoplay = VideoAutoplay;

  // init the VideoAutoplay object
  var videoAutoplay = document.getElementsByClassName('js-video-autoplay');
  if( videoAutoplay.length > 0) {
		for(var i = 0; i < videoAutoplay.length; i++) {
      new VideoAutoplay(videoAutoplay[i]);
		}
	}
}());

Make sure to add the .js-video-autoplay class to all the video elements you want to target.


🎥 Demo video by invisiblepower on Pexels.

Categories

Bug report & feedback

Component Github page ↗

Project duplicated

Project created

Globals imported

There was an error while trying to export your project. Please try again or contact us.