vendredi 15 février 2019

Conditionally load video for different devices - JavaScript

I would like to load different videos depending of the user's device using javascript. But i'm not able to accomplish this, the video won't show up :-/

My html:

<div id="fullsize-video-bg">
  <video id="video-bg-test-mobile" preload="metadata"></video>
  <video id="video-bg-test-desktop" preload="metadata"></video>
</div>

My javascript:

function loadVid(){

  if (window.matchMedia("(min-aspect-ratio: 1/1)").matches) {

    var videourl = 'https://example.com/video-bg-test-desktop.mp4';
    var videocontainer = '#fullsize-video-bg';
      var parameter = new Date().getMilliseconds();

      var video = '<video width="1920" height="1080" id="video-bg-test-desktop" autoplay loop muted playsinline src="' + videourl + '?t=' + parameter + '"></video>';

      $(videocontainer).append(video);

      video = $(document).find('#video-bg-test-desktop')[0];

      video.load();
    }

  else {

    var videourl = 'https://example.com/video-bg-test-mobile.mp4'; 
    var videocontainer = '#fullsize-video-bg';
      var parameter = new Date().getMilliseconds();

      var video = '<video width="768 " height="1366" id="video-bg-test-mobile" autoplay loop muted playsinline src="' + videourl + '?t=' + parameter + '"></video>';

      $(videocontainer).append(video);

      video = $(document).find('#video-bg-test-mobile')[0];

      video.load();
  }
}

I also made a Pen: https://codepen.io/mcmc/pen/YBJeqd

Aucun commentaire:

Enregistrer un commentaire