LEDIK
LEDIK

Reputation: 63

How to change video js source with a link click

I'm trying to create a simple website with few anime episodes. I have a question about javascript. How can I change video source by clicking on one of my links? I understand, that I have to use event listeners and just change the <source> depending on what link I click, but I'm not that good at programing or googeling. The video player I'm using is "video js".

If I could get an help I'd be really thankful.

the section of video code:

        <div class="sidebar">
            <a href="">Episode 1</a>
            <a href="">Episode 2</a>
        </div>
        <div class="main">
            <h1>Click the "play button" to start watching!</h1>
            <video
            id="my_video"
            class="video-js"
            controls
            preload="auto"
            width="640"
            height="300"
            poster="bg2.jpg"
            data-setup="{}">
            <source src="1-1.mp4" type="video/mp4" />
            <source src="1-1.webm" type="video/webm" />
            <p class="vjs-no-js">
                To view this video please enable JavaScript, and consider upgrading to a
                web browser that
            <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a>
            </p>
            </video>
        </div>

I would add the javascript file too, but my brain can't write anything useful there :)

Upvotes: 2

Views: 1463

Answers (4)

user11031046
user11031046

Reputation:

You could do something like this:

Javascript:

function ChangeSrc(Src) {
    document.getElementById('my_video').src = Src + '.mp4';
}

HTML:

<a onclick="changeSrc('1')">Episode 1</a>
<a onclick="changeSrc('2')">Episode 2</a>

Oh sorry, someone already answered something like this. Sorry.

Upvotes: 1

Martin Vogt
Martin Vogt

Reputation: 26

Please find enclosed a small demo and the code.

https://codepen.io/hellomartin-the-scripter/pen/GRZLXJv

HTML:

<a href="#" onclick="changeSource('1-1')">Episode 1</a>
<a href="#" onclick="changeSource('1-2')">Episode 2</a>
<a href="#" onclick="changeSource('1-3')">Episode 3</a>

<!-- SOURCE TAGS -->
<source id="video-mp4" src="#" />
<source id="video-webm" src="#" />

Script:

function changeSource(episode) {
  document.getElementById("video-mp4").src=episode + '.mp4';
  document.getElementById("video-webm").src=episode + '.webm';
}

Upvotes: 1

Harrison Pugh
Harrison Pugh

Reputation: 113

You need to give the source an element id and then use getElementbyid command to modify it and that should work like it does in the answer of this question

How to change video source onclick?

Upvotes: 0

spacesven
spacesven

Reputation: 15

I think the Answer by Ryan in this post can help you with this problem: How to change video source onclick?

Upvotes: 0

Related Questions