Amar Pawar Amar Pawar - 5 months ago 36
jQuery Question

How to change video source onclick?

HTML:

<div class="source" id="source_one" onclick="chnageToSourceTwo()">
Source 1
</div>
<video id="example_video_1" class="video-js vjs-default-skin vjs-big-play-centered" controls preload="none" width="640" height="360" poster="" data-setup="{}">
<source src="example_video_1.mp4" type='video/mp4' />
</video>


Script:

function chnageToSourceTwo() {
document.getElementById("example_video_1").src="example_video_2.mp4";
}


The video source is not changing after clicking on div. I am using the Video.js plugin to add video player to my webpage.

Does anyone know how to change source of video onclick?

jsFiddle http://jsfiddle.net/ah1fj7te/

Answer

It would be easier is to give your <source> object an ID. and reference the object by the ID using document.getElementById and document.addEventListener

Change your HTML:

<div class="source" id="source_one">Source 1</div>
<video id="example_video_1" class="video-js vjs-default-skin vjs-big-play-centered" controls preload="none" width="640" height="360" poster="" data-setup="{}">
    <source id="source_video" src="example_video_1.mp4" type='video/mp4' />
</video>

<script>
  document.getElementById('source_one').addEventListener('click', function() {
    document.getElementById('source_video').src = 'example_video_2.mp4';
  });
</script>