I am trying to change the subtitle tracks dynamically on button click using the following lines of code.But it is not changing the subtitles.why?
$('#turnoff').click(function(){
$('.player-content-video track').attr('default',false);
});
$('#english').click(function(){
$('.player-content-video track').attr('default',false);
$('.player-content-video track').eq(0).attr('default',false);
});
$('#chinese').click(function(){
$('.player-content-video track').eq(1).attr('default',false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video class="player-content-video">
<track src="sample_video-en.vtt" srclang="en" kind="subtitles" default="true">
<track src="sample_video-ch.vtt" default="false" srclang="ch" kind="subtitles">
<source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>
<br/>
<button id="turnoff" >NO SUBTITLE</button>
<button id="english" >ENGLISH</button>
<button id="chinese" >CHINESE</button>
NOTE: The track
src
in this example is only for code demonstration.
If you need to change the default
attribute on your track
tag you could use the following script:
Working example, please inspect the DOM to see the result (as video and track src are not present):
https://jsfiddle.net/3hh9kvgd/
You can use jQuery :eq() Selector
in the following way.
More info can be found here.
$('.player-content-video track:eq(0)')
By the way using :eq()
make your code dependent of your <track>
position in the DOM and require transverse all DOM when User click on a button, which is not really good approach in term maintainability and perfomance.
You could instead, reference your <track>
by id and cache your DOM selection when using jQuery.
$('#turnoff').click(function(){
$('.player-content-video track').attr('default',false);
});
$('#english').click(function(){
$('.player-content-video track').attr('default',false);
$('.player-content-video track:eq(0)').attr('default',true);
});
$('#chinese').click(function(){
$('.player-content-video track').attr('default',false);
$('.player-content-video track:eq(1)').attr('default',true);
});
<video class="player-content-video">
<track src="sample_video-en.vtt" srclang="en" kind="subtitles" default="true">
<track src="sample_video-ch.vtt" default="false" srclang="ch" kind="subtitles">
<source src="myvideo.mp4" type="video/mp4">
</video>
<br/>
<button id="turnoff" >NO SUBTITLE</button>
<button id="english" >ENGLISH</button>
<button id="chinese" >CHINESE</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With