Changing video resolution on HTML 5.0 video with JavaScript - javascript

UPDATE: I was using the Fotorama plugin and it seems that the bottom menu was causing the problem. Disabling that menu by putting div-tags around the video-tags made the function for setting resolution work. Thanks for the help and encouragement. For the bottom menu I create a simple one using link buttons that link to a similar page with the next video.
I have written JavaScript code that changes the resolution of a video based on input of a option/select-element. It works. The problem is that it stops working when I put exactly the same code inside a function (so that the code can be executed multiple times - each time option/select-element is changed.)
Here is an image of the videoplayer and the option/select-element I have added
Here is the code for the option/select-element:
<li class="porfolionav">
<select id="selectQuality" onchange="changeVidQualityFunction()">
<option value="1080" selected="selected" disabled="disabled">Videokvalitet</option>
<option value="1080" id="1080">HD 1080</option>
<option value="480" id="480">SD 480</option>
<option value="320" id="320">SD 320</option>
</select>
</li>
Here is the code for the videos:
<div class="fotorama" data-width="1209px" data-height="680px" data-allowfullscreen="false" data-arrows="true" data-click="true" data-swipe="true" data-autoplay="false" data-transition="slide" data-clicktransition="slide" data-shuffle="false">
<video id="video1V" height="680px" controls data-caption="320 OGG" poster="videos/img/thumb1.jpg">
<source src="videos/test_q_320" id="video1">Your browser does not support HTML5 video.
</video>
<video id="video2V" height="680px" controls data-caption="480 OGG" poster="videos/img/thumb2.jpg">
<source id="video2" src="videos/test_q_480.ogg" id="video2">Your browser does not support HTML5 video.
</video>
<video id="video3V" height="680px" controls data-caption="1080 OGG" poster="videos/img/thumb3.jpg">
<source id="video3" src="videos/test_q_1080.ogg" id="video3">Your browser does not support HTML5 video.
</video>
</div>
And here is the code for the changing resolution (works when not in a function):
<script>
function changeVidQualityFunction(){
$chosenVidQuality = document.getElementById("selectQuality").value;
$trulycompletevideolink = document.getElementById("video1").src;
$step1 = document.getElementById("video1").src.split("_q_");
//COMMENT: step1[0] is the url from start and including the first part of the filename (not the "_q_"-part and the format)
$upToVidName = $step1[0];
//COMMENT: step1[1] is the resolution and format, e.g. 320.ogg
$step2 = $step1[1].split(".");
//COMMENT: step2[0] is the resoltion e.g. 720 ,step2[1] is the format (without the dot in front of the format type) e.g. ogg
$vidresolution = $step2[0];
$vidformat = $step2[1];
$vidresolution = $chosenVidQuality;
$result = $upToVidName+"_q_"+$vidresolution+"."+$vidformat;
$('#video1').attr('src', $result);
$('#video1V').attr('data-caption', $vidresolution+" OGG");
$('#video1V').load();
window.alert("video1 attr src:"+document.getElementById("video1").src); //shows updated URL
}
</script>
Thanks

On your head tag place this <script src="jquery-1.12.2.js" charset="utf-8"></script> to include jquery library since your are using functions from jquery.
and from this line
<select id="selectQuality" onchange="changeVidQualityFunction()">
change it to
<select id="selectQuality" name="video_selected">
and edit your script that follows the rule of jquery, make proper declarations as follows.
function changeVidQualityFunction() {
var ev = $('#selectQuality').val();
console.log(ev);
var chosenVidQuality = $('#selectQuality').val();
var trulycompletevideolink = document.getElementById("video1").src;
var step1 = document.getElementById("video1").src.split("_q_");
//COMMENT: step1[0] is the url from start and including the first part of the filename (not the "_q_"-part and the format)
var upToVidName = step1[0];
//COMMENT: step1[1] is the resolution and format, e.g. 320.ogg
var step2 = step1[1].split(".");
//COMMENT: step2[0] is the resoltion e.g. 720 ,step2[1] is the format (without the dot in front of the format type) e.g. ogg
var vidresolution = step2[0];
var vidformat = step2[1];
vidresolution = chosenVidQuality;
var result = upToVidName + "_q_" + vidresolution + "." + vidformat;
$('#video1').attr('src', result);
$('#video1V').attr('data-caption', vidresolution+" OGG");
$('#video1V').load();
window.alert("video1 attr src:"+document.getElementById("video1").src); //shows updated URL
}
notice that I remove $ of the variable although this is valid, an declare it with var so javascript will know that they are variables.
$(document).ready(function(){
$('#selectQuality').change(function(){
changeVidQualityFunction();
});
});
What the code do is, it will track for a change on your drop down, if change, the function will execute.
Hope this will help

I was using the Fotorama plugin and it seems that the bottom menu was causing the problem. Disabling that menu by putting div-tags around the video-tags made the function for setting resolution work. Thanks for the help and encouragement. For the bottom menu I create a simple one using link buttons that link to a similar page with the next video.

Related

How to get JS to execute for whole class?

I have many videos on my page and I've created and extra button on the video to speed up video, and it is working if I call getElementById.
Is it possible to use one Javascript for all videos on the page? Since it's around 80+, then would be lots of duplicated javascript code, as I also have to make button to go back to speed 1x
HTML page block looks like this.
....
<div class="LigthBox">
<a href="javascript:Play1();" class="speed1">
<video class="Video_LitBox" id="DVD101" controls preload="none" poster="img/DVDThb-101.png"> <source src="res/vid-str.php?play_video=101" type="video/mp4"> </video>
<h3 class="DVid_title">101 Intro </h3>
<p class="DVid_body">101 Intro description .....</p>
</div>
....
and below in script area I have the following:
<script type="application/javascript">
var vid = document.getElementById("DVD101");
vid.onended = function() {
alert("The video has ended");
fireEvent( document.getElementById('clVid1'), 'click');
}
function Play1() {
vid.playbackRate = 1;
}
function Play15() {
vid.playbackRate = 1.5;
}
</script>
so variable vid to be somehow defined for every video on the page or any other work around if any. btw fireevent also doesn't work after video finishes, alert shows but doesn't close the the window.
You should maybe change the selector, instead of using getElementById() method you should try :
document.querySelectorAll('video')
which will return an array with all video instances. Then, you can easily do whatever you want with a simple for...in or forEach loop.
More details about querySelectorAll() method.
For anyone interested in solution. Thanks to #Aaron_Actu suggestion and some digging I ended up making just one short JS with argument (video-speed)
so call from html looks the same for all videos
....
....
and at the bottom of the page script looks like
....
function PlaySpeed(vspd) {
var vid = document.querySelectorAll('video');
for (var i=0; i<vid.length; i++) {
vid[i].playbackRate = vspd / 10;
}
}
...
I pass "video-speed" with 10x multiplier so that argument is an integer

Random Fullscreen Video Background on Load (jsfiddle included)

Trying to get my site to display a random fullscreen background video from a folder of videos I will maintain. I'd like to keep adding to the folder (bg1.mp4, bg2.mp4, etc...) and have the code automatically choose a random video to loop when you load the page.
here is my current code: https://jsfiddle.net/nenr3kyn/2/ , which isn't fully functional. I have a specific video chosen as the source file:
<source src="http://thenewcode.com/assets/videos/polina.mp4" type="video/mp4">
because I can't seem to get the html to call the variable set by the javascript "vid", like this:
<source src=vid type="video/mp4">
Also, this code wouldn't allow me to simply add files to the folder, and is limiting me to the videos that are specifically listed in the code. I'd rather have the javascript able to count all the files currently in the folder and choose a random, but couldn't get that to work either.
Any ideas?
Any input is greatly appreciated.
Thanks so much!!
Don't use the loop attribute it wouldn't trigger the ended event.
videoPlayer.addEventListener('ended', function(){
var videoLink = ['link1', 'link2','link3'];
var nextVid = Math.floor( Math.random() * videoLink.length);
this.src = videoLink[nextVideo];
this.play();
});
Hope this will help

Load different video in HTML5 video player

I have an HTML5 video tag that I dynamically load. Here's my HTML:
<video id="video" width="640" height="480" controls autoplay>
<source id="source" src="" type="video/mp4">
</video>
Here is my JavaScript for loading the video:
function RunVideo(index) {
var grid = document.getElementById("ctl00_ContentPlaceHolder1_gvPresentations");
var cell = grid.rows[(+index) + 1].cells[2].innerHTML;
var player = document.getElementById('video');
var mp4Vid = document.getElementById('source');
var movie = cell;
player.pause();
mp4Vid.setAttribute('src', movie);
player.load();
player.play();
}
The first time I load a video (from a grid view) it works fine. But any subsequent ones I try to load I get the following message in the video player:
Error: Unsupported video type or invalid file path.
How can I correctly unload the current video in order to reload a new one?
Edit
It seems to be an IE only bug. It does work in other browsers like a charm.
It is able to play each video individually on load (i.e if no other src have been set before).
The links and code are ok then.
It throws a MEDIA12899: AUDIO/VIDEO: Unknown MIME type. error.
Edit:
After I tested with this fiddle, the bug doesn't raise, so my assumptions were incorrect.
Which leaves you with the only choice of trying to re-encode your videos.
Original answer:
It seems you are facing an IE bug, when setting the source element with different codecs(not type).
I think that the browser automatically assigns for himself the codec parameter, in the type attribute and doesn't update it when the new src is set.
Even if all your videos are encapsulated in .mp4, the codecs may vary.
You can find a list of codecs that IE does support here. Basically, .webm, '
H.264 high profile' and H.264 baseline profile.
One possible workaround you may try, if my assumptions are correct, is to create a new sourceelement each time you call your RunVideo function.
function RunVideo(index) {
var grid = document.getElementById("ctl00_ContentPlaceHolder1_gvPresentations");
var cell = grid.rows[(+index) + 1].cells[2].innerHTML;
var player = document.getElementById('video');
var oldMp4Vid = document.getElementById('source');
var movie = cell;
var newmp4Vid = document.createElement('source')
newMp4Vid.src = cell;
player.removeChild(oldMp4Vid);
player.appendChild(newMp4Vid);
player.load();
}
I'm not sure it will do the trick and I'm not sure what the specs tells about setting <source> new src on the flow like that, but if this problem is only present in IE, it's probably a bug from them, maybe you could fill a bug report.
Alternatively, you could re-encode your videos with the exact same codec.

How to force a html5 video to load fully?

I have a few html5 videos on a page. When I first enter the page, they load correctly - I can see the correct frame size, play the video etc. etc. After going to another page and coming back to the video page the frames are not high enough and the video doesn't play, doesn't go fullscreen etc.
In my opinion it's something with video loading. I tried using onloadeddata without success (I might have used it wrong though, newbie here).
Is there any way the video can be forced to load? Like a loop checking if the videos are loaded, if not - loading them?
UPDATE: Here's the code.
var content = '';
var index;
$.post('api/getVideo.php', {id: id}, function(data) {
//console.log(data);
for (index = 0; index < data.length; index++) {
content = content + '<div class="col-md-6 video-col"> <button id="play" class="full-play-button"><i class="fa fa-play"></i></button>' +
'<video id="video1" class="video-small"> <source src="'+data[index]["Path"] + '"type="video/'+data[index]["Typ"]+'" class="video-file"> </video><h3 class="video-title">'+
data[index]["Tytul"]+'</h3></div>';
}
}, "json");
You might have a typo in your source tag. Try changing '"type="video/' to '"type=video/"'. Modern browsers don't require the type attribute, anymore, so try removing '"type="video/'+data[index]["Typ"]+' completely. I don't have enough info to test your code, but it looks like a syntax error.
From MediaAPI docs,
The Media API also contains a load() method which: "Causes the element to reset and start selecting and loading a new media resource from scratch." (
Load element causes browser to run media element load algorithm)
You can trigger load while returning back from the new page.
In short this is not fully possible. For short videos you can set the preload attribute to "auto" or the empty string "". This means, that you want the browser to preload the source entirly.
Unfortunatley, in case of long videos, the video isn't fully downloaded by most browsers. In case of mobile browser explicitly iOS. The preload attribute doesn't work. So the way to this look like this:
<video preload="" controls="">
<source src="my-video.mp4" type="video/mp4" />
<source src="my-video.webm" type="video/webm" />
</video>

Video selection using <select> tag does not work

I am implementing a video selection functionality to my video play so that people can choose which video they would like to watch. My current code goes like this:
html:
<video id="media" width="600" height="400" preload="none">
<source id="myvideos" src="files/Best of 60s.m4v"> </source>
</video>
<select id="videos">
<option value="PleaseSelect" selected="selected">Please Select...</option>
<option value="files/Best of 60s.m4v">Best of 60s</option>
<option value="files/Black and White Gems.m4v">Black and White Gems</option>
</select>
Javascript:
var selectmenu, mmedia;
selectmenu=document.getElementById('videos');
mmedia = document.getElementById('media');
selectmenu.addEventListener('onchange', loadvid);
function loadvid(){
selectmenu.onchange=function(){
var chosenoption=this.options[this.selectedIndex];
if (chosenoption.value != "PleaseSelect"){
mmedia.src = chosenoption.value;
}
mmedia.load();
}
}
When I run this code no "link" gets created between what I choose in the select menu to what plays except for what I have stated in the src element.
I implemented this with the following mindset:
To have an onchange event attached to the select element so the function loadvid() only fires off when something changes in the menu.
The loadvid function than manages the choice of video by defining the value of the selected index and passing it to mmedia; which is a video element and has the src property.
Once the selection is made the video then should load (mmedia.load()).
I have obviously gone wrong somewhere and would appreciate any guidance you can provide.
Many thanks.
Your javascript has an "onchange" where "change" is needed; in addition extraneous function is commented out below:
var selectmenu, mmedia;
selectmenu = document.getElementById('videos');
mmedia = document.getElementById('media');
selectmenu.addEventListener('change', loadvid);
function loadvid() {
//selectmenu.onchange=function(){
var chosenoption = this.options[this.selectedIndex];
if (chosenoption.value != "PleaseSelect") {
alert(chosenoption.value);
mmedia.src = chosenoption.value;
}
mmedia.load();
// }
}
The other problem you're going to encounter is using <source> in your <video> tag; you might have less trouble if you simply use a src= attribute in the video tag:
<video name="media" id="media" width="600" height="400" preload="none" src="files/Best of 60s.m4v"></video>
You're on the right track, however, there is a "typo" preventing your code from working:
In your addEventListener call, you tell it to listen for onchange which isn't an actual event. MDN has a handy list of events. You'll want to use the change event instead.
The on prefix is used when you add a listener directly as a HTML attribute like so <select onchange="loadvid()">.
Side-note: Since you've already attached an event listener here:
selectmenu.addEventListener('change', loadvid);
...You don't need to do it again here:
function loadvid(){
selectmenu.onchange=function(){
Take care of those 2 and you get this working code:
var selectmenu, mmedia;
selectmenu = document.getElementById('videos');
mmedia = document.getElementById('media');
selectmenu.addEventListener('change', loadvid);
function loadvid(){
var chosenoption=this.options[this.selectedIndex];
console.log(chosenoption);
if (chosenoption.value != "PleaseSelect"){
mmedia.src = chosenoption.value;
}
mmedia.load();
}

Categories