Switch videos within the video tag as you scroll

I am trying to implement a video tag within a div element on my website. Here is the current code:

<div class="phone" align="center">
  <div class="phone-inner">
    <video width="100%" height="100%" autoplay="" loop="" muted id="phonevideo">
      <source src="vid/1.mp4" type="video/mp4">
    </video>
  </div>
</div>

My goal is to change the video displayed based on which section of the page is currently in view. For example, when "div two" is in view, I want to switch the video, and then do so again for "div three" or "div four." This functionality can be seen on fueled.com. Here is the existing JavaScript code that needs modification to achieve this:

$(window).scroll(function() {
  var topDivHeight = $("#first").height();
  var DivTop = $("#sixth").position().top;
  var viewPortSize = $(window).height();

  var triggerAt = 450;
  var triggerHeight = (topDivHeight - viewPortSize) + triggerAt;
  var test1 = (topDivHeight - viewPortSize) + 650;

  var count = 0;
  var number = jQuery.grep(mainTops, function(n, i) {
    if (n < $(window).scrollTop())
    {
      count++;
    }
  });

   $('.nav ul li a').css("color", "#fff");
   $('.nav ul li a#nav'+count ).css("color", "#f60");
  if($(window).scrollTop() >= triggerHeight && $(window).scrollTop() < DivTop) {
    $('.phone').css('visibility', 'visible').fadeIn();
    if($(window).scrollTop() >= test1){
      $('#phonevideo').html('<source src="vid/2.mp4" type="video/mp4">'); // tried using this method but its not working here. Some other method needed here.
    }
  } else {
    $('.phone').fadeOut();
  }
});

Answer №1

Give this code a try:

$('#phonevideo').find("source").attr("src", "https://www.example.com/video.mp4");
$('#phonevideo').get(0).load();

If you want to change the video source, use

$('#phonevideo').find("source").attr("src","newvideosource")

After updating the video source, ensure to load it using $('#phonevideo').get(0).load()

Answer №2

Instead of replacing the HTML directly with the function .html(), you have to follow the guidelines set out in the HTML specification.

If a source element is already inserted into a video or audio element, dynamically modifying it and its attributes will not have any effect.

However, as recommended by the documentation, you can change what is being played. Just update the src attribute on the media element directly and then use the function .load().

Here's a functional example:

var btn = document.getElementById('btn'),
    player = document.getElementById('phonevideo'),
    source = document.getElementById('src');
btn.addEventListener('click', function(event) {
  player.pause();
  source.src = 'http://html5demos.com/assets/dizzy.mp4'; // change the video
  player.load(); // load it
});
<div class="phone" align="center">
  <div class="phone-inner">
    <video width="100%" height="100%" autoplay="" loop="" muted id="phonevideo">
      <source id="src" src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4" type="video/mp4">
    </video>
  </div>
</div>
<button id="btn" type="button">Change Video!</button>

To achieve this using jQuery (not tested), you can try the following code:

var player = $('#phonevideo');
player.find("source").attr("src", "http://html5demos.com/assets/dizzy.mp4");
player[0].load();

Answer №3

Your code has been enhanced through optimization. A new class has been added to your divs along with the use of data attribute. You can view the updated version on jsfiddle.

<div class="phone" align="center">
  <div class="phone-inner">
    <video width="100%" height="100%" autoplay="" loop="" muted id="phonevideo">
      <source src="vid/1.mp4" type="video/mp4">
    </video>
  </div>
</div>

<div id="first" class="view" data-vid-src="vid/1.mp4"></div>
<div id="two" class="view" data-vid-src="vid/2.mp4"></div>
<div id="three" class="view" data-vid-src="vid/3.mp4"></div>
<div id="four" class="view" data-vid-src="vid/4.mp4"></div>
<div id="five" class="view" data-vid-src="vid/5.mp4"></div>
<div id="six" class="view" data-vid-src="vid/6.mp4"></div>

For visual representation, I've applied some CSS:

.phone {
  position: fixed;
  height: 200px;
  width: 120px;
  background: white;
  top: 50%;
  left: 50%;
  margin-top: -100px;
  margin-left: -60px;
}

.view {
  height: 500px;
}

#first {
  background: red;
}

#two {
  background: yellow;
}

#three {
  background: green;
}

#four {
  background: blue;
}

#five {
  background: pink;
}

#six {
  background: black;
}

Let's move on to the jQuery implementation.

function getCurrentElement(pos) {
  var len = $('.view').length;
  var i = 0;
  var old_pos;
  var ele_pos;
  var old_ele;
  var return_ele;
  $('.view').each(function(){
    i++;
    offset = $(this).offset();
    ele_pos = offset.top;
    if(pos == ele_pos) {
      return_ele = $(this);
      return;
    }
    else if(ele_pos > pos && old_pos < pos) {
      return_ele = old_ele;
      return;
    }
    else if(ele_pos < pos && i == len) {
      return_ele = $(this);
      return;
    }
    old_pos = ele_pos;
    old_ele = $(this);
  });
  return return_ele;
}
var old_ele = null;
$(window).scroll(function() {
  var cur_pos = $(window).scrollTop();
  current_element = getCurrentElement(cur_pos);
  if(old_ele != null) {
    if(current_element.attr('id') != old_ele.attr('id')) {
      $('#phonevideo source').attr('src',current_element.attr('data-vid-src'))
    }
  }
  old_ele = current_element;
});

This optimized code is designed to be more efficient and helpful. Enjoy! :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Animate a jumping figure using jQuery

Is it possible to create an animation of a person jumping from the bottom of the screen to the top, with the scroll bar following them? I have my doubts but would love to know if it can be done. If you want to see what I mean, check out this PDF: http:// ...

Crockford's method of replacing values with nested objects

/** Custom Supplant Method **/ String.prototype.customSupplant = function(obj) { return this.replace (/{([^{}]*)}/g, function (match, propPath) { var props = propPath.split('.'); var result = obj; f ...

The authentication for npm failed with a 401 error code when attempting to log in

When attempting to sign in to npm using the command npm login and providing my username, password, and email, I am encountering the following error message: The Registry is returning a 401 status code for the PUT request. Even though I have used the sa ...

When an express pre-remove signal initiates another pre-remove action during the removal process

Imagine having 4 different models structured like this: ┌────────────┐ ┌────────────┐ │ User │ │ Goal │ ├────────────┤ 1 ├───── ...

Various inline SVG elements not rendering properly on HTML page

I have converted several PDF files to SVG using a tool called pdftocairo. These SVG files can be viewed in a browser without any issues. You can find one of the SVG files here. However, when I try to embed multiple different SVG files into the same HTML ...

Dynamic properties in JQuery

Here is the HTML DOM element I have... <input type="text" style="width: 200px;" id="input1"/> I want to make sure it stores date values. How can I specify that in the DOM element? Please provide your suggestions. Thanks! ...

Alternative solution for :has selector in Firefox without relying on JavaScript

Currently I am building a small website for a friend and incorporating the :has pseudo class. However, Firefox does not support this feature by default, unless manually enabled. Are there any workarounds available in this case? I am creating a hamburger m ...

Ways to refresh the main frame

Here is an example of parent code: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Parent</title> </head> <body> <iframe src="https://dl.dropboxusercontent.com/u/4017788/Labs/child.html" width ...

The request is being redirected to an invalid destination, resulting in

I am facing an issue with a simple Jquery dialog box on my website. The dialog contains a button that sends the page to the server for processing. However, after some checking, the server redirects the page to another link. The problem arises when I use r ...

Monitor the DOM for visibility changes in Selenium WebDriver and PjantomJS before proceeding

I am currently creating automated test scripts using selenium-webdriver, phantomJS, and mocha. The script file I'm working with is a JavaScript file. My goal is to wait until an element (<a>) is fully visible before clicking on it. Let me pro ...

"Encountered an error while trying to locate the view" in a simple Express.js application

Embarking on the journey to learn Express.js, I decided to create a simple Express app. The structure of my app.js is as follows: var express = require('express'); var app = express(); app.configure(function(){ app.set('view engine&ap ...

Application experiencing server error when updating MongoDB data

I have encountered an issue while trying to update/modify data that has already been uploaded in a reactjs project using mongoDB as the database. Whenever I attempt to update the data, an error is displayed. How can this problem be resolved? https://i.sta ...

"Access denied: Resteasy and ajax do not support this method (error

Encountering a login problem, although registration is functioning smoothly. Tech stack - HTML/AJAX/JQuery->Resteasy (Wildfly 10.1.0 Final) The URL - https://www.test.com/login.html - (actual URL name altered) Upon submitting the form with method type ...

Modifying the color of a non-active tab - Material UI Tabs

Is there a way to customize the color of inactive tabs in Material UI tabs? I have noticed that they currently appear black, as shown in the screenshot here: screenshot Thank you! ...

There was an issue with the SidebarController function being undefined, as it was expected to be a function

I'm encountering two issues with my demo: Error: [ng:areq] Argument 'SidebarController' is not a function, received undefined http://errors.angularjs.org/1.2.26/ng/areq?p0=SidebarController&p1=not%20aNaNunction%2C%20got%20undefined ...

Ensure that the footer remains at the bottom of the page without being fixed to the bottom

I am currently working on configuring the footer placement on pages of my website that contain the main body content class ".interior-health-main". My goal is to have a sticky footer positioned at the very bottom of these pages in order to eliminate any wh ...

The content within a div block is having trouble aligning vertically

I need help with centering the content inside my fixed-top navigation bar vertically. I am using bootstrap to design my page, and the navigation bar consists of an image as the nav header and a container with links. The container surrounding these element ...

Issues regarding the CSS navigation bar

I'm currently working on creating a navigation bar using HTML and CSS. However, I'm facing an issue where the nav-bar doesn't extend to the full width of the page as intended. I've attempted adjusting the padding-left: 0px and padding-r ...

How to access the api variable in JavaScript

When attempting to retrieve variables from an API object, I encountered the obstacle of them being nested inside another object named "0" in this particular case. Here is a screenshot from the console: enter image description here Below is the JavaScrip ...

Padding for the initial element in a carousel display

I am currently working on implementing owl carousel with stage padding. My goal is to use the carousel with loop:false, and have the first item displayed without left padding, while maintaining consistent padding for both items on the left and right after ...