videojs dynamic source update not working - javascript

I had this running before but after few years it seems it has stopped working.
Using videojs v7.3.0, and the plugin codebase is located in the local project directory itself.
<link rel="stylesheet" type="text/css" href="<?php echo Utility::getAssetsPath('videojs/video-js.min.css'); ?>" >
<script src="<?php echo Utility::getAssetsPath('videojs/video.min.js'); ?>"></script>
<div id="light">
<a class="boxclose" id="boxclose" onclick="lightbox_close();"></a>
<video id="video_player_frame" class="video-js vjs-default-skin" controls preload="none" width="595" data-setup="{}">
<source src="http://vjs.zencdn.net/v/oceans.mp4" type="video/mp4">
<!--Browser does not support <video> tag -->
<p class="vjs-no-js">Javascript is disabled.</p>
</video>
</div>
<a href="javascript:void(0);" onclick="lightbox_open(this);" data-link="<?php echo $list['file_path']; ?>">
</a>
I had to add a default video source or else it threw No Compatible source was found for this media.
function lightbox_open(el) {
/* load link to video source attribute */
var link_string = el.getAttribute('data-link');
var video_player_el_src = document.getElementById('video_player_frame').getElementsByTagName('source')[0];
video_player_el_src.setAttribute('src', link_string);
videojs('video_player_frame').ready(function() {
lightBoxVideo = this;
/** check if the video is already viewed
* if not, push link to viewed_video_arr,
* and load the player
**/
if(!viewed_video_arr.includes(link_string)) {
viewed_video_arr.push(link_string); /* store the video link to the array */
lightBoxVideo.load(); /* reload the video player */
}
window.scrollTo(0, 0);
document.getElementById('light').style.display = 'block';
document.getElementById('fade').style.display = 'block';
lightBoxVideo.play();
});
}
This used to work but it seems it doesn't support updating the source this way.
Since the codebase for the library is not pulled from some CDN I think it should have worked the way it was working earlier.
Any idea where it went wrong?

Instead of lighbox.load(); you should load the actual <video> element (not at the <source> tag level).
Untested code example:
function lightbox_open(el)
{
//# load link to video source attribute
var link_string = el.getAttribute('data-link');
//var video_player_el_src = document.getElementById('video_player_frame').getElementsByTagName('source')[0];
//video_player_el_src.setAttribute('src', link_string);
let video_player_el_src = document.getElementById('video_player_frame');
video_player_el_src.setAttribute('src', link_string);
videojs('video_player_frame').ready( function()
{
lightBoxVideo = this;
/** check if the video is already viewed
* if not, push link to viewed_video_arr,
* and load the player
**/
if(!viewed_video_arr.includes(link_string))
{
//# store the video link to the array
viewed_video_arr.push(link_string);
//# reload the video player
//lightBoxVideo.load();
video_player_el_src.load();
}
window.scrollTo(0, 0);
document.getElementById('light').style.display = 'block';
document.getElementById('fade').style.display = 'block';
lightBoxVideo.play();
});
}

Related

Randomize Background Video with Sound, after clicking function

I wrote this code a while back, and it allowed users to click and refresh the page to autoplay a RANDOM background video with sound.
This is the function that they click that loads the function
https://pastebin.com/0XXEHvQQ
<div align="center">
<p><font face="verdana" size="2">
<a onclick="ok()"> press me PLAY VIDS :)</a></font></p>
</div>
https://pastebin.com/PD5qdNDM
<div align="center">
<p><font face="verdana" size="2">
<a onclick="ok()"> -> press me to fix the site :) <-</a></font></p>
</div>
</div>
</div>
</div>
<!-- Scripts -->
<script src="js/parallax.js"></script>
<script>
// Pretty simple huh?
var scene = document.getElementById('scene');
var parallax = new Parallax(scene);
</script>
</script>
<script src="js/custom.js"></script>
<script>
let volumeInterval;
function loaded(){
setInterval(loop, 600);
volumeInterval = setInterval(volume, 1);
}
function unload(){
for (var i = 1; i < 99999; i++)
window.clearInterval(i);
console.log("unloaded");
}
function volume() {
try {
document.getElementsByTagName("video")[0].volume = 0.15;
console.log("done!");
clearInterval(volumeInterval);
}
catch (e) {
console.log("waiting..");
}
}
function ok() {
document.write(unescape(
and heres the unescaped code
https://pastebin.com/YJwbG2mC
<!-- VIDEO GRABBB -->
<video preload="auto" autoplay="true" loop="true">
<source id="player" src="5.mp4">
<script>
var video = document.currentScript.parentElement;
video.volume = 0.33;
//document.getElementById('player').currentTime = 20;
</script>
<script>
var video = document.getElementById("player");
video.addEventListener("timeupdate", function(){
if(this.currentTime >= 1000) {
location.reload();
}
});
</script>
<script type="text/javascript">
var video = document.getElementsByTagName('video')[0];
video.onended = function() {
location.reload();
};
</script>
<script>
document.getElementById("player").src = "/" + Math.floor((Math.random()*7)+1) + ".mp4";
</script>
</video>
No matter how I try to adjust the unescaped code, I can't get the MP4 to autoplay after clicking the function.
Here is my live site that I no longer can access: form.wtf
According to the HTML Spec on the Source Element,
Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unnecessarily complicated approach.
Therefore, no matter what you do to the source element, you can't change the video unless the new src is applied directly to the video element.
Replacing the source element also has no effect on the video that plays. The source element's src attribute may changed but the video will keep on playing.
Therefore, you should leave your source's src attribute empty until the JavaScript code sets it or
Leave out the source tag all together and apply the src straight to the video.
Math.floor(Math.random() * 7 + 1); is exactly the same thing as Math.ceil(Math.random() * 7);
document.querySelector('#player > source').src = `/${Math.ceil(Math.random() * 7)}.mp4`;
<video id="player" preload="auto" autoplay loop>
<source src="">
</video>

How to make a video play when you open a modal box using JavaScript?

I've been setting up a video page for my website and I'm trying to make it extra slick by using Javascript!... Unfortunately, I completely suck at Javascript! Ok, so here's my problem:
I've managed to make a modal box with an opening animation using HTML and CSS, now what I want to happen is as soon as I click the video thumbnails the video starts playing and when I click the close button, the video stops playing or pauses, I've managed to make it work using "onclick" commands... but it only works for one video!
I've tried setting up videos with multiple ids and multiple JS vars but none of them work, at some point I made it so all of the videos started playing at once even though I only had one modal box open... lol
Here's a snipet of my current code:
<!-- Open the Lightbox with these images -->
<div class="row">
<div class="column">
<img src="tsr/teaserthumbnail.png" onclick="openModal();currentSlide(1);playVid()" class="hover-shadow">
<img class="play-btn" src="/assets/play-btn.png" onclick="openModal();currentSlide(1);playVid()">
</div>
<div class="column">
<img src="tsr/e3thumbnail.png" onclick="openModal();currentSlide(2);playVid()" class="hover-shadow">
<img class="play-btn" src="/assets/play-btn.png" onclick="openModal();currentSlide(2);playVid()">
</div>
</div>
<!-- Modal/Lightbox Content -->
<div id="myModal" class="modal">
<span class="close cursor" onclick="closeModal();pauseVid()">×</span>
<div class="modal-content">
<div class="mySlides">
<center><video id="myVideo" width="100%" controls src="tsr/TSR_TeaserMovie_PEGI_ENG_1527074582.mp4"></video></center>
</div>
<div class="mySlides">
<center><video id="myVideo" width="100%" controls src="tsr/TSR_E3_Trailer_UK_PEGI_1528474075.mp4"></video></center>
</div>
<script>
// Open the Modal
var vid = document.getElementById("myVideo");
function openModal() {
document.getElementById("myModal").style.display = "block";
}
function playVid() {
vid.play();
}
// Close the Modal
function closeModal() {
document.getElementById("myModal").style.display = "none";
}
function pauseVid() {
vid.pause();
}
Here's the webpage itself if you need anymore context:
https://sonic.retro-media.net/videos/tsr.php
All I really need is for each video to start playing when I click the thumbnail or pause when I close the modal/lightbox.
Thanks in advance!
Can you just call playVid() from the openModal() when that function is running?
One solution you can try is to set autoplay=1 when the modal is opened too, that way the video starts playing. You can do the same to stop the video when 'closeModal()' is called by setting autoplay=0.
This is how you would add the autoplay to the current src of the video if it's in an iframe:
vid.src = vid.src + (vid.src.indexOf('?') < 0 ? '?' : '&') + 'autoplay=1';
Here is a more complete version of the code.
var autoplayVideo = function (modal) {
// Look for a YouTube, Vimeo, or HTML5 video in the modal
var video = modal.querySelector('iframe[src*="www.youtube.com"], iframe[src*="player.vimeo.com"], video');
// Bail if the modal doesn't have a video
if (!video) return;
// If an HTML5 video, play it
if (video.tagName.toLowerCase() === 'video') {
video.play();
return;
}
// Add autoplay to video src
// video.src: the current video `src` attribute
// (video.src.indexOf('?') < 0 ? '?' : '&'): if the video.src already has query string parameters, add an "&". Otherwise, add a "?".
// 'autoplay=1': add the autoplay parameter
video.src = video.src + (video.src.indexOf('?') < 0 ? '?' : '&') + 'autoplay=1';
};
Now to stop the video when the modal closes:
/**
* Stop a YouTube, Vimeo, or HTML5 video
* #param {Node} modal The modal to search inside
*/
var stopVideo = function (modal) {
// Look for a YouTube, Vimeo, or HTML5 video in the modal
var video = modal.querySelector('iframe[src*="www.youtube.com"], iframe[src*="player.vimeo.com"], video');
// Bail if the modal doesn't have a video
if (!video) return;
// If an HTML5 video, pause it
if (video.tagName.toLowerCase() === 'video') {
video.pause();
return;
}
// Remove autoplay from video src
video.src = video.src.replace('&autoplay=1', '').replace('?autoplay=1', '');
};
Don't forget to expose the button/thumbnail and the modal as arguments
modals.init({
callbackOpen: function ( toggle, modal ) {
autoplayVideo(modal);
},
callbackClose: function ( toggle, modal ) {
stopVideo(modal);
}
});
Let me know if this works!
Cheers!
I figured it out!
The solution was rather simple too, all I had to do to was edit the code to:
<script>
function playVid(vidID) {
var vid = document.getElementById(vidID);
vid.play();
}
function pauseVid(vidID) {
var vid = document.getElementById(vidID);
vid.pause();
}
</script>
Now all I had to do was change my video IDs accordingly, in this case 'myVideo1' and 'myVideo2'!
Thank you for your help!
Firefox - https://support.mozilla.org/en-US/kb/block-autoplay
Chrome - https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
autoplay is going to be turned off (more like, it's already off) by default on all major browsers, unless the user changes the browser autoplay settings.

Read Video path using javascript

How to read video path using javascript and pass it to html source value. Currently I am using hard coded from my html to read video and I want it to be dynamic to javascript. Here is my Temporary loading from content folder in my project:
<video id="video" controls preload="metadata" style="width:100%; height:100%">
<source src="~/Content/Videos/Sample_Vid.mp4" type="video/mp4">
</video>
If I understand your question correctly then you could:
implement a function like setVideoSource() as shown below, which would allow you to set/change the source of a video element that already exists in your page or,
implement a function like addVideo() as shown below, which would allow you to dynamically create/add a new video element to your page with a source of your choosing
Please see the documentation below for detail on how both functions work:
/*
Updates the source of first video in the document matching the selector
*/
function setVideoSource(selector, src) {
const element = document.querySelector(selector);
/*
Check that element is video before proceeding
*/
if(element.nodeName === 'VIDEO') {
/*
If element is a video, remove any source children if present
*/
for(const source of element.querySelectorAll('source')) {
element.removeChild(source);
}
/*
Create a new source element and populate it with the src
attribute
*/
const source = document.createElement('source');
source.setAttribute('src', src);
/*
Add source element to the video we're updating
*/
element.appendChild(source);
}
}
/*
Adds a new video to the document under the first element matching the parentSelector
*/
function addVideo(parentSelector, src, width, height) {
const parent = document.querySelector(parentSelector);
/*
Check that parent exists before proceeding
*/
if(parent) {
/*
Create new video element
*/
const video = document.createElement('video');
video.setAttribute('controls', true);
if(width) {
video.setAttribute('width', width);
}
if(height) {
video.setAttribute('height', height);
}
/*
Create a new source element and populate it with the src
attribute
*/
const source = document.createElement('source');
source.setAttribute('src', src);
/*
Add source element to the video we're inserting and add
the video element to the document element
*/
video.appendChild(source);
parent.appendChild(video);
}
}
// Update source of existing video
setVideoSource('#video', 'https://www.w3schools.com/html/mov_bbb.mp4')
// Add a new video to the page
addVideo('#parent', 'https://www.w3schools.com/html/mov_bbb.mp4', '100%', '150px')
<h3>Existing video dynamically updated with JavaScript</h3>
<video id="video" controls preload="metadata" style="width:100%; height:100%">
<source src="~/Content/Videos/Sample_Vid.mp4" type="video/mp4">
</video>
<h3>New video dynamically added to page with JavaScript</h3>
<div id="parent">
</div>
Hope that helps!

HTML5 Video If hash is equal to value set the audio to 1 else set the audio to 0 using Javascript Functions

Hello I am trying to set the HTML5's video audio level depending on the location hash for example if the hash is #home the video's audio should be 1.0 if the hash isn't #home then the audio level should be 0.0
I've had a play around and i can't seem to get it to work here is my code
and thank you for taking a look and for any help!
$(function() {
if (location.hash === "#home") {
videoAudio();
}
} else {
videoAudioMute();
});
function videoAudio() {
var vid = document.getElementById("myvideo");
vid.volume = 1.0;
}
function videoAudioMute() {
var vid = document.getElementById("myvideo");
vid.volume = 0.0;
}
html
<div class="background">
<video id="myvideo" poster="assets/img/slide1-background-img-pattern-01.jpg" controls="" autoplay="" loop="" >
<source src="assets/vid/Background.mp4" type="video/mp4">
<source src="assets/vid/Background.webm" type="video/webm">
<source src="assets/vid/Background.ogv" type="video/ogg">
</video>
</div>
You have a syntax error.
The correct version should be like:
$(function () {
if (location.hash === "#home") {
videoAudio();
} else {
videoAudioMute();
}
});
function videoAudio() {
var vid = document.getElementById("myvideo");
vid.volume = 1.0;
}
function videoAudioMute() {
var vid = document.getElementById("myvideo");
vid.volume = 0.0;
}
To give a proper answer to the question I think we need a little bit more information.
What you can do if you do not want to share more is console log location. This should give you an object with some properties in it. Hash is one of them. Check it and see if you are getting the data that you expect. If hash is not giving what you want you can try using some of the other properties as an identifier, like pathanme.
If the problem is not in the hash but it is in manipulating the audio level you can try jQuery. I have had a lot of headaches manipulating audio and video files with JavaScript but I have found that jQuery work the best.
Hope this helps.

Start playing HTML5 Video only after the complete video is buffered

Is there a way I can start playing my HTML5 MP4 video only after the entire video is buffered (100%). When it is in the process of buffering, I should display the Loading screen. Please help. This code should work in both Firefox and IE11.
Hyperlink Titles Example :
- Play Video1: Fav Foods - Play Video1: Fav Veg - Play Video2: Fav Animal
And here is the code I have when I click on the hyperlink and also the Video tags. I load the video dynamically from the database. The attribute 'pos' tells the time in seconds where the player has to seek playing.
<video id="VideoContainer" controls="controls" style="width:500px;height:320px" preload="auto">
<source id="VideoData" src=#Model.IntroVideoPath type="video/mp4" />
Your browser does not support the video tag.
<a onclick="navVideo('#items.FileName','#items.StartSec');">#items.DisplayText</a>
function navVideo(fileName, pos) {
//Get Player and the source
var player = document.getElementById('VideoContainer');
var mp4Vid = document.getElementById('VideoData');
var mp4CurVid = $(mp4Vid).attr('src');
//Reload the player only if the file name changes
if (mp4CurVid != fileName) {
$(mp4Vid).attr('src', fileName);
player.load();
player.play();
if (pos != 0) {
setTimeout(function () {
player.currentTime = pos;
player.play();
}, 1000);
}
}
else {
player.pause();
player.currentTime = pos;
player.play();
}
The problem was with the encoding technique for that MP4 file. I encoded with different settings (random settings options for Mp4) and finally got that to work without buffer.
You could use the this http://videojs.com/ to get that to work.

Categories

Resources