Desii
Desii

Reputation: 25

Changing video source javascript

My solution: http://jsfiddle.net/g7mrs/22/

function loadVideo(event) {
  videojs("myPlayer").src({ 
    type: "video/youtube",
    src: "https://youtu.be/ZSn3Tvc7jQU"
  });
  event.preventDefault();
}                

I got a working solution, however I would like to have only 1 function instead of 4

Any ideas?

Upvotes: 0

Views: 45

Answers (2)

Rabbi Shuki Gur
Rabbi Shuki Gur

Reputation: 1716

Adding on to @hsz answer, You can also add the first part of the url to the function, and just send the ID.

This will also help if you need to later on change your video provider, since you only will have to change the base (assuming that the id stays the same).

So your JS function:

var base = 'https://youtu.be/';

function loadVideo(id) {
    videojs("myPlayer").src({ type: "video/youtube", src: base + id });
    event.preventDefault();                  
}

end then in the HTML

<a href="#" onClick="loadVideo('ZSn3Tvc7jQU')">video</a>

Upvotes: 0

hsz
hsz

Reputation: 152206

You can pass YouTube URL as a parameter:

function loadVideo(url) {
    videojs("myPlayer").src({ type: "video/youtube", src: url});
    event.preventDefault();                  
}

And in HTML:

<a href="#" onClick="loadVideo('https://youtu.be/ZSn3Tvc7jQU')">video</a>
<a href="#" onClick="loadVideo('https://youtu.be/0BhSrfNgLxs')">video2</a>

Upvotes: 1

Related Questions