Skip to content Skip to sidebar Skip to footer

Changing

I'm testing on building a site locally on my machine using bootstrap. I have a

Solution 1:

Just get the viewport size, and based on that value, pause the video, change the src link, load the new video and play the new video.

But do note that you will need to refresh the page after changing the browser size to see the video change.

If you want the video to change whenever the screen resizes as well as on page refresh, you will first need to move the above JavaScript to a function and run it when a resize event is fired. Then, for the page load, you need to remove the video element from your HTML and add it on page load using the createElement() method with the src attribute value also added depending on the viewport width.


Check this JSFiddle or run the following Code Snippet for a practical example of what I have described above:

/* JavaScript */

  var w = window.matchMedia("(max-width: 700px)");
  var vid = document.getElementById("vid");
  var source = document.createElement("source");
  source.id = "hvid";
  source.setAttribute("type", "video/mp4");
  vid.appendChild(source);
  
  if (w.matches) {
    vid.pause();
    source.removeAttribute("src");
    source.setAttribute("src", "https://storage.googleapis.com/coverr-main/mp4/Love-Boat.mp4");
    vid.load();
    vid.play();
  } else {
    vid.pause();
    source.removeAttribute("src");
    source.setAttribute("src", "https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4");
    vid.load();
    vid.play();
  }

window.addEventListener("resize", function(){
  var w = window.matchMedia("(max-width: 700px)");
  var vid = document.getElementById("vid");
  var source = document.getElementById("hvid");
  
  if (w.matches) {
    vid.pause();
    source.src = "https://storage.googleapis.com/coverr-main/mp4/Love-Boat.mp4";
    vid.load();
    vid.play();
  } else {
    vid.pause();
    source.src = "https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4";
    vid.load();
    vid.play();
  }
});
/* CSS */

html, body {margin: 0; padding:0; width: 100%; height: 100%;}.row{display: block !important;}
<!-- CDN Links -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" />

<!-- HTML -->

<div class="container">
  <div class="row">
    <video id="vid" class="col-12" loop muted autoplay></video>
  </div>  
</div>

Post a Comment for "Changing