Is there a way to switch the video source when a particular h3 tag is clicked?

https://i.sstatic.net/I2gIZ.jpgI'm currently working on building a video streaming site, but I've hit a roadblock.

My challenge right now is figuring out how to make the episode selector change the video player's source. I'm a bit confused about how to accomplish this and also how to dynamically change the text below the player based on the selected video.

    <div class="container">
        <div class="main-video">
            <div class="video">
                <video src="video link here"></video>
                <h3 class="ep-title">00. Prologue</h3>
            </div>
        </div>

        <div class="episode-list">
            <div class="episode active">
                
                <img src="image link here" alt="">
                <h3 class="title">00. Prologue</h3>
            </div>
            <div class="episode">
                <img src="image link here" alt="">
                <h3 class="title">01. A Winter Day, A Fateful Night</h3>
            </div>
            
        </div>
    </div>

<script>
    let listVideo = document.querySelectorAll('.episode-list .episode');
    let mainVideo = document.querySelector('.main-video video');
    let title = document.querySelector('.main-video .title')

    listVideo.forEach(video =>{
        video.onclick = () =>{
            listVideo.forEach(episode => episode.classList.remove('active'));
            video.classList.add('active');
            };
        
    });
</script>

This is the current structure of my webpage code (excluding the navigation bar and plyr code). I know my question might seem a little complex, but any guidance or assistance would be greatly appreciated :)

Answer №1

const changeBtn = document.getElementById('change-url');
const videoPlayer = document.getElementById('video');

changeBtn.addEventListener('click', () => {
   console.log(videoPlayer);
   videoPlayer.setAttribute('src', 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4');
})
<button id="change-url">Change URL</button>
<br/><br/>

<video id="video" src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" width="300px" controls autoplay></video>

Answer №2

In order to change the video src, you can utilize

mainVideo.setAttribute('src', YOURSOURCELINK);
. To update the title text, simply use
title.innerHTML = "NEWTEXT"

For instance:

The parameter "index" refers to the position in the list (remember that JavaScript starts counting from 0 for the first item). Therefore, to display episode one, you would call changeVideo(0), and for episode two, changeVideo(1), and so on.

var list = [{
    title: "Episode 1",
    src: "some source link"
},{
    title: "Episode 2",
    src: "second source link"
}];


function changeVideo(index){
    let mainVideo = document.querySelector('.main-video video');
    let title = document.querySelector('.main-video .title')

    mainVideo.setAttribute("src", list[index].src)
    title.innerHTML = list[index].title

}

Next, ensure you have an onclick event in your video selection - e.g., include

onclick="changeVideo(1)"
within your
<div class="episode">

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

Activate the button in React after ensuring all form fields are populated

Hello everyone, I'm new to using React and I'm trying to implement some basic validation but I'm struggling. Here are my goals: Disable the button if any form fields are empty Enable the button only when ALL form fields are are filled I w ...

Having trouble with the input range slider on Chrome? No worries, it's working perfectly fine

I'm currently facing an issue with an input range slider that controls the position of an audio track. It seems to work perfectly in Firefox, but in Chrome, the slider gets stuck and doesn't move when dragged. There is a function in place that up ...

The element will only show up upon resizing (in Safari web browser)

I am facing a problem with a button styled using the class btn-getInfo-Ok <button class="btn-getInfo-Ok">Hello</button> in my style.css file .btn-getInfo-Ok { color:white !important; margin: 0 auto !important; height:50px; bottom:0; ...

Refreshing the page results in a 404 error when utilizing React Router

I am currently facing an issue with my web application setup. Back-End My back-end consists of a Node.js/express server that serves files in response to specific requests made to certain routes. Front-End On the front-end, I have React pages that commu ...

What is causing the modal to fail to open when the button is clicked?

My HTML includes a modal that isn't functioning correctly. <!doctype html> <html lang="en"> <head> <title>Rooms</title> <meta charset="utf-8"> <meta name="viewport" conte ...

Close popup after submitting the form

On my website, I have a function to submit a form within a modal. Everything works well except for when I uncomment a certain line of code. When I uncomment that line, my test mysql insert on the page /index.php/trainings/add doesn't get executed. I a ...

Is there a Facebook application embedded in the user's wall?

Is it feasible to create a website similar to YouTube, where users can share it on Facebook and run the app (in this case, the video player) directly on their wall without having to visit the YouTube page? If it is possible, is this functionality limited ...

Boxes not occupying entire vertical space

My structure is unique, like a 9-box with div elements: <div class="NBWrapper"> <div class="NBTopRow"> <div class="NBLeft" /> <div class="NBRight" /> <div class="NBMiddle" /> </div> & ...

"Encountering a problem with jQuery AJAX - receiving an error message despite the status code being

Attempting to make a jQuery Ajax request using the following code: $.ajax({ url: '<MY_URL>', type: 'POST', contentType: 'application/json;charset=UTF-8', data: JSON.stringify(data), dataType: 'a ...

Modify the characteristic of a personalized directive

I have created a unique directive that allows me to load pages within a specified div element. .directive('page', function () { return { templateUrl: function (elem, attr) { return 'pages/page-' + attr.num + &ap ...

"Encountering an issue with the live preview feature in Br

Currently, I am working on a project offline and trying to make Brackets' live preview feature work smoothly. It has proven to be quite convenient for my tasks. While opening my project files using the "open file" option in Brackets, I encountered an ...

How to automatically change the input to sentence case as the user types in Angular 8

Hey guys, I'm having an issue with my input field. I want the text to display in sentence case as I type, but it keeps showing up in title case. For example, if I type "hello hai how are you", it displays as "Hello Hai How Are You" ...

What is the importance of using mb_convert_encoding in order to display the characters correctly?

My website and MySQL database are both set to use UTF-8 encoding. An issue I am encountering is that when retrieving text from the MySQL database to display on the website, I need to utilize the PHP function mb_convert_encoding(@db_field,'utf-8' ...

"I encountered an error stating that res.json is not a function while trying to establish a connection between ReactJS

dataset.list.js import React, { Component } from "react"; import Datasets from "./data"; import axios from "axios"; class App extends Component { render() { return <Datasets datasets={this.state.datasets} />; } ...

A guide to invoking a function from another component in Angular

analytics.js fetchAnalyticsData() { this.loading.today = true; this.loading.daily = true; const metrics = ['VISITS', 'PAGE VIEWS', 'CONVERSION RATE', 'BOUNCE RATE']; const analyticsModules = [ ...

Analyze the elements within arrays and determine the occurrence rate of each element

Issue at hand: var rawData = [[two],[three],[four],[one],[two],[two],[two],[three],[four],[five],[three],[four],[five]]; Given an array of arrays, the goal is to identify the unique elements within one of the arrays and provide a count of each unique ele ...

Guide to customizing margins at specific breakpoints in Bootstrap 4 without using javascript

Despite exploring numerous solutions and trying them out, I have yet to achieve the desired results. I am looking to customize margins for various breakpoints in Bootstrap. For example: View for laptops, Tablet view The issue may be related to defined w ...

Unable to retrieve the most recent value from the PHP session

Is there a way to retrieve the most up-to-date value of a session without needing to refresh the page? I am looking for a solution that allows me to assign dynamic values to a variable based on which button is clicked. However, I am currently facing the i ...

Tips for implementing WebSockets in a NativeScript application

Is there anyone who can provide guidance on utilizing WebSockets in NativeScript? I am working with VueJS in NativeScript and attempting to retrieve data using ws. Any assistance on this matter would be greatly appreciated. Thank you ...

What is the best way to delete a JavaScript file in Mobile Safari using JavaScript?

One of the files causing issues on my website is a Javascript file that is affecting the display specifically on iPad devices using Mobile Safari. I am looking to exclude this file only on iPads and serve it to all other browsers. Below is the Javascript ...