0

I'm currently working on making a fullscreen video background. Usually for touch devices (iPad, iPhones, etc.) I would just hide the video element with css and display an image instead.

Out of curiosity I went to see what responsive solutions different websites are using for their html5 video backgrounds. That's when I noticed that AirBnB is not loading the html5 video element at all on touch devices (I tested on iPad and iPhone, I havn't tested on android yet). If you inspect the website on a touch device you will notice that the video element is completely "gone".

So my question is, what is the best way to prevent html5 videos from being loaded on touch devices?

Preferably with php or jquery (I also have modernizr loaded to my site.).

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
lassemt
  • 164
  • 1
  • 11

2 Answers2

1

In Javascript:

if("ontouchstart" in document.documentElement){
    var video = document.querySelectorAll("video")[0];
    var img = document.createElement("img");

    //set img attributes here

    video.parentNode.replaceChild(img, video);

}

The problem of CSS media queries is that you cannot detect touch devices directly.

Claudio King
  • 1,606
  • 1
  • 10
  • 12
0

The easiest cross-browser method would be to have a placeholder element, like:

<img src="background-img.jpg" data-video-src="video.mp4" class="video-placeholder" />

You simply have a listener for clicks on your elements that have the style video-placeholder and replace with the html5 video element.

Something like:

$('body').on('click','.video-placeholder', function(event) {
  //Create video element
  var videoSrc = $(this).data('video-src');
  var video = $('<video></video>');
  video.load(function() { /*Do onload stuff*/ });
  video.attr('src',videoSrc);
  //Replace element
  $(this).replaceWith(video);
});

This is obviously a very simplified solution, but it gives you an idea how to handle it so you don't autoload a video unless the user wants to play it.

MiltoxBeyond
  • 2,683
  • 1
  • 13
  • 12