Skip to content Skip to sidebar Skip to footer

Loading HTML Video With JQuery

So what I am trying to to is load different video based on the screen size of the device. Here is my jQuery: var v = new Array(); v[0] = [ 'header.webm', 'header.ogv',

Solution 1:

Since you already have jQuery in your project, use it:

HTML:

<video autoplay="" loop="" poster="" id="bgvid">
  <source id="webmvid" src="" type="video/webm">
  <source id="oggvid" src="" type="video/ogg">
  <source id="mp4vid" src="" type="video/mp4">
</video>

JS:

var v = [];

v[0] = ["header.webm", "header.ogv", "header.mp4"];
v[1] = ["mobHead.webm", "mobHead.ogv", "mobHead.mp4"];

var index = window.innerWidth <= 641 ? 1 : 0;

$('#webmvid').attr('src', v[index][0]);
$('#oggvid').attr('src', v[index][1]);
$('#mp4vid').attr('src', v[index][2]);

Basically I just made your if-case shorter and targeted each video src with an Id and jQuery.


Solution 2:

Try This (add id to each < source > and reference them in js):

HTML:

<video autoplay="" loop="" poster="" id="bgvid">
  <source id="src1" src="" type="video/webm">
  <source id="src2" src="" type="video/ogg">
  <source id="src3" src="" type="video/mp4">
</video>

JS:

v1 = { 
webm: "header.webm", 
ogv: "header.ogv", 
mp4: "header.mp4"
} 

v2 = {
webm: "mobHead.webm", 
ogv: "mobHead.ogv", 
mp4: "mobHead.mp4"
};

if(window.innerWidth >= 642){
  $('#src1').attr("src", v1.webm);
  $('#src2').attr("src", v1.ogv);
  $('#src3').attr("src", v1.mp4);
}
else
{
  $('#src1').attr("src", v2.webm);
  $('#src2').attr("src", v2.ogv);
  $('#src3').attr("src", v2.mp4);
}

Post a Comment for "Loading HTML Video With JQuery"