Is it possible to have multiple links that redirect a video to different sources?

I've been experimenting with creating multiple links that can change the source of the video being played on a player when clicked.

Although I have come close to achieving my desired outcome, there is still one hurdle remaining:

Here's the HTML code snippet:

<video id="videoclip" width="640" height="480" controls preload="none">
<source id="mp4video" src="myvideo.mp4?dl=1">
</video>

<p><a href="#videoclip" id="videolink1">first video</a></p>
<p><a href="#videoclip" id="videolink2">second video</a></p>
<p><a href="#videoclip" id="videolink3">third video</a></p>
<p><a href="#videoclip" id="videolink4">fourth video</a></p>

And here's the corresponding Javascript code:

videocontainer = document.getElementById('videoclip');
videosource = document.getElementById('mp4video');
newmp4 = 'newvideo.mp4?dl=1';

videobutton = document.getElementById("videolink1");

videobutton.addEventListener("click", function(event) {
    videocontainer.pause();
    videosource.setAttribute('src', newmp4);
    videocontainer.load();
    videocontainer.play();
}, false);

While this current setup works well, it only allows me to switch between the first and second videos. My ultimate goal is to be able to click any of the other links (i.e., videolink2, videolink3, etc.) and have the corresponding video play instead.

Despite scouring various resources for hours, I haven't been able to overcome this challenge just yet.

Answer №1

In scenarios like this, you must approach it with a dynamic mindset. Your initial method to get one video working serves as a valuable foundation.

Now, each video link is equipped with a data- attribute containing the new source for that specific link.

All video links share the same class, enabling us to group them together using

document.getElementsByClassName("videolink")
, which returns an array of elements with the classname videolink.

Subsequently, iterate over the returned array (comprising link elements with the classname videolink) and attach a click event to each, triggering the changeVideo function.

this within the changeVideo function points to the clicked element. Utilize the dataset property on the clicked link element to access the value stored in data-videolink.

Finally, update the video source to reflect that value.

var videocontainer = document.getElementById('videoclip');
var videosource = document.getElementById('mp4video');
var videoButtons = document.getElementsByClassName("videolink");

for (var i = 0; i < videoButtons.length; i++) {
  videoButtons[i].addEventListener("click", changeVideo, false);
}

function changeVideo() {
  var newLink = this.dataset.videolink;
  console.log("Changing video to source: " + newLink);
  //videocontainer.pause();
  //videosource.setAttribute('src', newLink);
  //videocontainer.load();
  //videocontainer.play();
}
<video id="videoclip" width="640" height="480" controls preload="none">
<source id="mp4video" src="myvideo.mp4?dl=1">
</video>

<p><a href="#videoclip" data-videolink="newvideo.mp4?dl=1" class="videolink">first video</a></p>
<p><a href="#videoclip" data-videolink="newvideo2.mp4?dl=1" class="videolink">second video</a></p>
<p><a href="#videoclip" data-videolink="newvideo3.mp4?dl=1" class="videolink">third video</a></p>
<p><a href="#videoclip" data-videolink="newvideo4.mp4?dl=1" class="videolink">fourth video</a></p>

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

Troubleshooting: CSS Selectors Hover Functionality Not Functioning as

I am having an issue where the styling does not change the display to block when hovering. Any insights or feedback would be greatly appreciated. <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="t ...

Querying mongoose with $near or other fields

I'm trying to retrieve documents using a query $or on different fields along with a $near query that is causing issues. Schema locationSchema{ ... beacon: String, access_point: String, gps: [], ... } locationSchema.index({ gps: ...

Struggling to retrieve JSON data from within an array

[ { "May": [ { "year": 1994, "date": "2" }, { "Sequence": 2, "Type": "Images" } ], "_id": "1122" } ] The issue I am facing is retrieving the id except for the "date" f ...

Retrieve a Vue Component by utilizing a personalized rendering method for a Contentful embedded entry

Currently experimenting with Contentful, encountering some issues with the Rich text content field. To customize the rendering of this block and incorporate assets and linked references in Rich text content, I am utilizing the modules '@contentful/ri ...

Creating a dynamic table in AngularJS with rotating values for rows and columns

I am seeking assistance in creating a table with a custom number of rows and columns. The table should have two input fields for specifying the number of rows and columns, and upon submission, the table should dynamically adjust to display the specified nu ...

Tips for displaying the contract form as text within an iPad app

Looking to develop an iPad application that includes a form for users to enter their name and date, with other fields already hard coded as shown in the example form. Which control should be used to achieve this functionality - is a TextView or webView mor ...

Vue Error: The function slugify is not defined

Currently, I am working on a feature where I want to extract the value from one input field, convert it into a slug format, and display it in another input field. This project involves Laravel Spark, Vue, and Bootstrap 4. Here is the content of my listing ...

What is the best approach to accessing a key within a deeply nested array in JavaScript that recursion cannot reach?

After hours of research, I have come across a perplexing issue that seems to have a simple solution. However, despite searching through various forums for help, I have reached an impasse. During my visit to an online React website, I stumbled upon the web ...

Socket.io continuously refreshing and updating multiple instances

Incorporating socket.io into a small React application, I configured all the listeners within the "componentWillMount" method. See the code snippet below for reference: componentWillMount() { const socket = io(); socket.on('update', f ...

Is there a reliable method for directing to the Google "I'm Feeling Lucky" result consistently?

I am currently working on a solution in my application to easily link to NFL player profiles on NFL.com using their names. Since the URL structure of the player profile pages on NFL.com is not consistent, I am attempting to generate a link to Google's ...

Exploring the reasons for utilizing class and ID selectors within a <div> element to enclose a map in OpenLayers

The 'quickstart' guide provides a comprehensive overview of using id and class css selectors within the html code. In order to link the map object to a specific div element, a target is required as an argument for the map object. This target val ...

The map function yields identical outcomes for all of the buttons

I need help with mapping an object that contains various note titles: ['note_title_test', 'note_title_test2', 'note_title_test32', 'note_title_test232', 'test title', 'testing1'] Below is the map ...

Text within table cells on email appears to be shrinking on Windows Phone devices

Can anyone help me understand why Windows Phone reduces the font size when text is placed within a table cell that isn't at 100% width or nested? Below is a screenshot of a test email template I'm working on. When I sent it to a Windows Phone 8. ...

Positioning a button on the side of the screen while a hidden side panel is open

I am attempting to create an animation using a side panel that will slide into view when a button is clicked. Here is how it appears when the page loads: https://i.sstatic.net/JPQ2W.jpg When the user clicks on one of the buttons, the notes panel will be ...

Display One Div at a Time in Sequence on Page Load Using jQuery

I have come across this question multiple times: How to Fade In images on page load using JavaScript one after the other? Fade in divs sequentially Using jQuery .fadeIn() on page load? Despite trying various recommended methods, I'm still unable t ...

Is there a way to modify the document title using .ready()?

As I work with nested layouts in Ruby on Rails, one particular layout requires me to extract a string from a div and use it as the title of the document. What is the proper method (if there is one) to accomplish this task? <script type="text/javascri ...

A step-by-step guide to summing two numbers within a list using vue.js

How do I calculate the average of the first 5 numbers in my list taken from the URL, grouped by 5-minute intervals? I have a delay of 1 minute to ensure there are 5 values within the initial 5 minutes. After that, I want to display the averages in 3 differ ...

What is the best way to upload an image along with optional information using multer?

How to send a File object from the frontend using React and FormData Output of files https://i.sstatic.net/gp61r.jpg Upon uploading a file, I am able to access the object in Multer and Express-Upload console.log(req.files.productImages) [{ &qu ...

JavaScript's Ajax request seems to be stagnant and inactive

Having some difficulties with the code below. It triggers an alert correctly, but the ajax part doesn't seem to be functioning. No errors or indications of what's wrong. $(document).on('change', '.department_select', function ...

Angular noticed a shift in the expression once it was verified

Whenever I try to invoke a service within the (change) action method, I encounter this issue: ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ng-untouched: true'. Cur ...