What is the best way to update the video source upon clicking a link with JQuery?

Is there a way to change the video src using jQuery when a link is clicked?

For example, if the user clicks on "#staff", the video src will be updated.

  <ul class="nav nav-pills" >
            <li role="presentation" class="loginPills"><a id="student" href="#">Student  </a></li>
            <li role="presentation" class="loginPills"><a id="staff" href="#">Staff</a></li>
            <li role="presentation" class="loginPills"><a id="employer"href="#">Employer</a></li>
        </ul>

Current video setup:

<video playsinline autoplay muted loop poster="" id="bgvid">
<source src="Border-Collies.mp4" type="video/mp4" id="mp4">

Attempted code (not functioning as expected):

$( document ).ready(function() {
$('#staff').on({
    'click': function(){
        $('#mp4').attr('src','The-Coast.mp4');
        $('#webm').attr('src','The-Coast.webm');
        console.log("click");
    }
});
});

Any help would be appreciated!

Answer №1

Your code is functioning properly, however, according to the specifications, dynamically changing the src attribute will not have any effect.

For more information, refer to https://dev.w3.org/html5/spec-preview/the-source-element.html

Modifying a source element and its attribute dynamically when it is already inserted in a video or audio element will not result in any changes.

Answer №2

To modify the video element, all you have to do is adjust the attribute within the video tag without changing the source tag. Here's how:

Simply replace

$('#mp4').attr('src','The-Coast.mp4');

with

$('#bgvid').attr('src','The-Coast.mp4')
;

Answer №3

Whenever you dynamically alter the src attribute of a source tag, don't forget to trigger the .load() method on the video element afterwards.

Let me demonstrate this for you.

document.getElementById('change').addEventListener('click', function(e) {
  e.preventDefault();
  document.getElementById('source').src = 'http://www.w3schools.com/html/mov_bbb.mp4';
  document.getElementById('video').load();
});
a {
  display: block;
  font-size: 2em;
}
<a href="#" id="change">click</a>

<video controls id="video">
  <source src="https://www.html5rocks.com/en/tutorials/video/basics/devstories.mp4" id="source">
</video>

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

Two boxes each taking up half of the width, with content placed inside a container

How can I achieve the appearance seen in this image? https://i.sstatic.net/2oZW8.png The layout consists of four columns using regular Bootstrap code. The first two columns should have a white background within a .container, while the other two columns s ...

Retrieving XML data from an external API is essential for integrating information

For a personal project, I am working on a mashup and trying to integrate a webservice that I came across. You can find the webservice here: Whenever I attempt to call it via ajax (using FireFox 7 in this case), I constantly encounter the following error ...

Sending values from multiple input fields created in PHP using AJAX can be done by following these steps

https://i.sstatic.net/GKcRc.png Within this snippet, there is a portion of a form that consists of 4 different fields/divs like the one shown. I am struggling to figure out how to send the values of these input fields to PHP using AJAX. I apologize if ...

Discovering the dimensions of images similar to Pinterest when fetching URLs with jQuery

Currently, I am in the process of developing a webpage that allows users to input a URL and extract images from it, similar to how Facebook, Pinterest, and The Fancy operate. Users input a URL and are provided with images that have a width greater than a s ...

Explore Site Configuration

When it comes to creating a responsive site with the given layouts: https://i.sstatic.net/esdpU.png https://i.sstatic.net/5Rdlr.png If you have a fixed header (4rem), how can you set up the main container (C & D) to have a maximum height of 100% and scr ...

Analyze items in two arrays using JavaScript and add any items that are missing

I am working on a JSON function that involves comparing objects in two different arrays, array1 and array2. The goal is to identify any missing items and either append them to array2 or create a new array called newArray1. Here is an example: const arra ...

Is there a non-table layout method to achieve equal width sharing with a fixed solution?

If I have n different elements to be placed in the same horizontal space, each taking up 100% of the screen width, for example: <table style="width:100%;text-align:center;table-layout:fixed"> <tr> <td><input/></td ...

What are the benefits of using React.useMemo or React.useCallback within component props?

Exploring efficient ways to implement TailwindCSS in React, considering its utility-first nature leading to component-heavy code (e.g. className="w-full bg-red-500"). One approach is creating a utility function like: utils/tailwind.ts const tw = (...clas ...

Determining Text Color Based on Background Hue

Is it possible to create a div that dynamically changes text color based on the background color surrounding it? I want the text to switch between two different colors, with the font color being the opposite of the background color. For example, black text ...

Utilizing two imports within the map() method

I have been considering the idea of incorporating two imports within map() in my React code. This is how my code looks: {this.state.dataExample.map(item => ( <ItemsSection nameSection={item.name} /> item.dat ...

Positioning of buttons in Bootstrap 5 tables

I am working on a table that represents a CRUD application with details of a person and edit/delete buttons. The goal is to have these buttons displayed side by side, even on smaller screen sizes where they currently stack on top of each other. How can I ...

What is the best way to align the text in the center of my h1 header?

Can anyone assist me with centering the contents of my h1 tag? h1{ width: 100%; vertical-align: middle; color: rgb(5, 5, 5); font-size:25px; letter-spacing: 0px; top: 0; text-align: left; padding: 10; }h1:after { content:' '; display: ...

There seems to be this strange and unexpected sharing of Animated.View and useRef between different child components

Currently, I am displaying a list of items in the following manner: {formattedJournal[meal].map((food, idx, arr) => { const isLast = idx === arr.length - 1; return ( <View key={idx}> ...

Reverse changes made to a massive object and then redo them

My current project requires the implementation of undo-redo functionality for a product. At the moment, I am managing a substantial Object retrieved from a MongoDB collection The structure is as follows: { cart:{ products:[ { name: " ...

When using the android phonegap application, the screen interface may not render properly and display a patch on the keypad area when the keypad is

Whenever I tap on a textbox, the system keypad pops up. But after entering text, if I click on any link instead of pressing the Go button on the keypad, the keypad disappears but leaves behind a random area or displays the previous screen. When navigating ...

Using AJAX to submit a form and then refreshing the page within the current tab

I am facing an issue with my web page that contains multiple tabs, some of which have forms. Whenever a form is successfully submitted, the page reloads but always goes back to the default first tab. To address this, I am attempting to use a storage variab ...

Building Nested Divs with JavaScript

I've encountered an issue with this code snippet. While it works perfectly fine in jsfiddle, I faced a problem when testing it on my local file. Only the first three lines created by html are displayed: test h1 test h2 test p (I tested the code ...

The parsing of Jquery ajax xml is not working as expected

Upon parsing my XML using the code below, everything was working fine until I added a review node. $(document).ready(function generatexml(){ $.ajax({ type: "GET", url: "data/concerts.xml", dataType: "xml", ...

Playbook Adobe Air application built with HTML encounters issue with reading "SQLConnection" property being undefined

I've encountered some issues while trying to run an HTML-based Adobe Air application. Everything works perfectly when executed in Aptana, but problems arise when I attempt to run the same file in Chrome, Firefox, or the BlackBerry Playbook simulator. ...

Utilizing dynamic meta tags in React JS with a PHP backend and Redux integration

Adding dynamic meta data like title, description, og_image, etc. in reactJs can be a bit complex. I've tried using the react-meta-tags package which changes the title and updates the meta data visible in my browser Inspector. However, when sharing on ...