HTML5 Video to play after AJAX page load - javascript

I am struggling to get an HTML5 video to play when arriving at the page via an AJAX request.
If you refresh the page, or land directly on the page, it works fine. But when navigating to the page via AJAX it does not play.
The code is:
<video id="video" autoplay="autoplay" loop="loop" muted="muted" poster="http://localhost/wp-content/themes/studioindigo/videos/contactbackground.jpg">
<source src="http://localhost/wp-content/themes/studioindigo/videos/contactbackground.mp4" type="video/mp4">
<source src="http://localhost/wp-content/themes/studioindigo/videos/contactbackground.webmhd.webm" type="video/webm">
<img src="http://localhost/wp-content/themes/studioindigo/videos/contactbackground.jpg" alt="your browser does not support html5 video">
</video>
I have tried firing the following code on success of AJAX page load:
video = document.getElementById('video');
video.load();
video.addEventListener('loadeddata', function() {
video.play();
}, false);
And also simply:
video = document.getElementById('video');
video.play();
I have also tried using plugins such as video.js, but to no avail.
I can't help but think I am missing something really simple. Surely if the video is on the page and has autoplay set, then it should just play regardless of whether you arrive at the page via AJAX or directly?
The AJAX request for the page only updates the #main element (which the video is inside) and the does history.pushState - could that be anything to do with it? It doesn't seem likely...

For anyone struggling with the same issue, I found that after the ajax call the video had the property 'paused: true' even thought autoplay was set and I was calling video.play() on 'loadeddata'.
The solution was to trigger video.play() when pause is detected. I also found that it worked smoother not having the 'autoplay' attribute on the video and became jerky after multiple initialisations.
DOM:
<video id="video" loop muted>
<source src="video.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
</video>
JS:
video = jQuery('#video').get()[0];
video.addEventListener('loadeddata', function() {
video.play();
});
video.addEventListener('pause', function() {
video.play();
});
Also, for anyone wondering why I might want this ability, it is for a video playing on the background of a webpage, hence no need for user to play/pause it.

you can call video.play() before your ajax calling.
like
html
<video id="video">...</video>
JS
function play() {
$("#video")[0].play(); // call play here !!!
$.ajax(
"your url",
{your data},
function() {
$("#video")[0].play(); // usually we call play() here, but it will be pause beccause it can not be play if not in click or touch event sync
....
}
);
}

Your video tag has no ID. What if you had two <video> tags? You want:
<video id="blah"...
and then:
video = document.getElementById('blah');

Potentially it's a syntax error, because you seem to have some PHP leaking into the HTML in the form of '; ?> at the end of the poster and src attributes.

It seems like these answers do not work anymore. I tried the accepted one, and it didn't work.
It looks like Chrome can't find the video object and it stands as undefined.
You can do something else. Quite simple. You use the Global Event Handlers .ajaxSuccess as a marker for that the request has been handled and the video can now play.
In that way you are sure that the video object exist. And for Chrome you do a little if statement.
video = jQuery('#video').get()[0];
jQuery( document ).ajaxSuccess(function( event, xhr, settings ) {
if( video ) {
video.play();
} else {
// Chrome can't find the video object and throws a 'undefined'
// Therefore you have to activate the video manually
jQuery("#videoID")[0].play();
}
});

Related

Will jQuery's remove() function cancel the request of the element

I'm wondering if jQuery's remove() function will reliably cancel requests that have been triggered during page load.
Given following setup:
<video>
<source src="movie1.mp4" type="video/mp4">
</video>
<video>
<source src="movie2.mp4" type="video/mp4">
</video>
and they are quite big videos to return in the response (~40mb).
When I have this in my JS:
$(document).ready(isMobile);
function isMobile() {
// condition that checks for mobile device here, next line executed if true
$('video').remove();
};
will the video already requested still be loaded? Will any of the videos be loaded?
As you can assume this is about cancelling unnecessary loading of videos which wouldn't be displayed for mobile anyway.
After running the following snippet, I noticed that it did indeed stop downloading the file after the current "chunk" finished downloading. This would prevent further loading by large sources.
$(document).ready(function() {
setTimeout(function() {
$('video').remove();
}, 10000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video src="https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_30mb.mp4" type="video/mp4" controls>
And after downloading/stopping 10 seconds in (The chunk finished downloading, and then stopped downloading more data):

Play HTML5 video after its loaded

I'm searching for a way to play html5 video after its fully loaded. And while video is still loading - showing video placeholder image.
Before i've used setTimeout function, but its not the way to accomplish this.
setTimeout(function() {
$('banner__video--fallback').fadeOut();
$('.banner__video')[0].play();
}, 800);
So what is the way around this to play video after its loaded?
EDITED:
With solution 'canplaythrough' video still start ot be playing before its fully loaded.
$('.banner__video')[0].addEventListener("canplaythrough", function () {
$('banner__video--fallback').fadeOut();
$('.banner__video')[0].play();
}, false);
Why don't you just use HTML5 video attributes? There's no need for javascript.
<video autoplay poster="/placeholder.jpg">
<source src="video.webm" type="video/webm">
<source src="video.mp4" type="video/mp4">
</video>
autoplay plays the video as soon as it is loaded and poster assigns an image to stand in the video while it's loading.
You should read more here: http://www.w3schools.com/html/html5_video.asp
I think this is a better option to play a video after its load:
var vid = document.getElementById("myVideo");
vid.oncanplaythrough = function() {
alert("Can play through video without stopping");
};
You can download video with ajax call like this:
Another: Force Chrome to fully buffer mp4 video or just use canplaythrough property.

Play full HTML5 video and then loop a section of it

I'm trying to play an 8.6 second video once completely, and then loop a small section of the video infinitely, to keep the illusion of a never-ending video. So far I've looked into the media fragments URI, and the ended event of the video. Setting the currentTime attribute in the ended event listener works, but it makes the video "blink".
At present, I'm using a timeupdate event listener to change the time when the video is approaching the end [shown below]
elem.addEventListener('timeupdate', function () {
if (elem.currentTime >= 8.5) {
elem.currentTime = 5;
elem.play();
}
}, false);
JSFiddle here
This works as well, but the video pauses visibly before restarting at 5 seconds. Is there a smoother way of playing the video once and then looping a segment of it?
Your code is fine, the problem is with your MP4 file! Try using a much smaller video like this one ( http://www.w3schools.com/tags/movie.mp4 ) to confirm the issue is not with your code.
So how can you achieve the same result but with large videos files?
You will need two video files:
video1 is the main video
video2 is the looping video
Remember: HTML5 video has no problem playing and looping large video files so we will use this method to play the videos.
In the example below we will play the first video and when it finishes we will execute a function to hide video1 and then show/play video2. (Video 2 is already set to loop)
Don't forget to load JQuery in your head otherwise this will not work.
<video id="video1" width="1080" height="568" poster="movie.png" autoplay onended="run()">
<source src="movie.webm" type="video/webm">
<source src="movie.ogg" type="video/ogg">
<source src="movie.mp4" type="video/mp4">
<object data="movie.mp4" width="1080" height="568">
<embed width="1080" height="568" src="movie.swf">
</object>
Optional test to be displayed if the browser doesn't support the video tag (HTML 5)
</video>
<video id="video2" width="1080" height="568" poster="loop.png" loop>
<source src="loop.webm" type="video/webm">
<source src="loop.ogg" type="video/ogg">
<source src="loop.mp4" type="video/mp4">
<object data="loop.mp4" width="1080" height="568">
<embed width="1080" height="568" src="loop.swf">
</object>
Optional test to be displayed if the browser doesn't support the video tag (HTML 5)
</video>
<script>
$( "#video2" ).hide();
function run(){
$( "#video1" ).hide();
$( "#video2" ).show();
document.getElementById("video2").play();
};
</script>
Try the following, to 'rewind' it as soon as it ends:
vidElem.addEventListener("ended", function () {
vidElem.currentTime = 2.5;
vidElem.play();
}, false);
Updated fiddle: http://jsfiddle.net/Lt4n7/1/
I just had to deal with the same problem and noticed the same issues with flickering. Here was my solution:
Get 2 videos (or sets of videos) - one for the non-looped section, the other for the looped section
Create 2 video elements
set the looping element to 'display:none'
Then just capture the ended event and swap display status (example uses jquery but you could use 'style.display="none/block"' just as easily:
VideoPlayer1 = document.getElementById('video1');
VideoPlayer2 = document.getElementById('video2');
VideoPlayer1.addEventListener('ended', videoLooper, false);
function videoLooper()
{
VideoPlayer2.play();
$(VideoPlayer2).show();
$(VideoPlayer1).hide();
}
You can't solve this issue in javascript. That delay you see depends on the video compression and the hardware.
To start playing at a time that is not 0, the video decoder has to go back and find a key frame and then build the current frame by reading everything between the last key frame and your chosen time.
I'm not an expert in video compression, but maybe there is a way to pick these key frames and place them exactly where you need them. I don't think it will be easy and smooth, though.
If you're looking for an easier solution, use #Random's, but it uses two <video> tags to work around this limit.
var iterations = 1;
var flag = false;
document.getElementById('iteration').innerText = iterations;
var myVideo = document.getElementById('video-background');
myVideo.addEventListener('ended', function() {
alert('end');
if (iterations < 2) {
this.currentTime = 0;
this.play();
iterations++;
document.getElementById('iteration').innerText = iterations;
} else {
flag = true;
this.play();
}
}, false);
myVideo.addEventListener('timeupdate', function() {
if (flag == true) {
console.log(this.currentTime);
if (this.currentTime > 5.5) {
console.log(this.currentTime);
this.pause();
}
}
}, false);
<div>Iteration: <span id="iteration"></span></div>
<video id="video-background" autoplay="" muted="" controls>
<source src="https://res.cloudinary.com/video/upload/ac_none,q_60/bgvid.mp4" type="video/mp4">
</video>
<div>Iteration: <span id="iteration"></span></div>
// Please note that loop attribute should not be there in video element in order for the 'ended' event to work in ie and firefox

Maximage 2.0 - HTML5 Video random start

I started using this great plugin : http://blog.aaronvanderzwan.com/2012/07/maximage-2-0/
The problem is that when reaching a slide containing a video, sometimes it does not start (in chromium at least). No errors thrown, it just seems to be a random behavior regarding to the video loading.
Any idea if there's a way to keep firing the browser detection or to try forcing the video play with some plugin options/controls?
Also, I could not find a way to add a play button to the page to play/pause the video...
Found it, you need to get your element, and then call the play() function :
The html for the video :
<video id="vid_1" poster="http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg" width="640" height="360">
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4" />
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm" type="video/webm" />
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.ogv" type="video/ogg" />
Your browser does not support HTML5 videos.
</video>
Then get the video element and fire the play :
//video play button
$('.play_button').click(function(){
var video = $('video#vid_1').get(0); //get the native browser source
if (video.paused) {
video.play(); //if paused, play
}
else{
video.pause(); //if playing, pause
}
});
So basically you can call it whenever you want...

Dynamically using the first frame as poster in HTML5 video?

I'm wondering if there's any straightforward way to achieve this effect, without needing backend code to extract a frame, save it as a jpg and database it somewhere.
An effect whereby the first frame of the video just shows up as the poster when the video loads would be so helpful (it would only work if the browser can play back the video obviously, which might be a little different from how poster traditionally works, but that is not a concern.
Did you try the following?
just append time in seconds #t={seconds} to source URL:
<video controls width="360">
<source src="https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/1080/Big_Buck_Bunny_1080_10s_1MB.mp4#t=0.1" type="video/mp4" />
</video>
I have chosen a fraction of second (0.1) to keep number of frames small, because I have the suspect that if you put 1 second, it would "preload" the first 1 second of video (i.e. 24 frames or more ....). Just in case ...
Works fine on Chrome and Firefox on desktop :)
Works not on Android mobile, though :(
I did not test on iOS, iPhone, IE yet ??
Edit May 2021:
I realized that many modern browsers now show automatically a poster of first frame.
Seems like they heard us :-)
To make it simple you can just add preload="metadata" to your video tag and the second of the first frame #t=0.5 to your video source:
<video width="400" controls="controls" preload="metadata">
<source src="https://www.w3schools.com/html/mov_bbb.mp4#t=0.5" type="video/mp4">
</video>
Best of luck!
There is a Popcorn.js plugin called Popcorn.capture which will allow you to create posters from any frame of your HTML5 video.
There is a limitation that is imposed by the browser that prohibits reading pixel data of resources requested across domains (using the canvas API to record the current value of a frame). The source video must be hosted on the same domain as the script and html page that is requesting it for this approach to work.
The code to create poster using this plugin is quite simple:
// This block of code must be run _after_ the DOM is ready
// This will capture the frame at the 10th second and create a poster
var video = Popcorn( "#video-id" );
// Once the video has loaded into memory, we can capture the poster
video.listen( "canplayall", function() {
this.currentTime( 10 ).capture();
});
I recently did this for a recent project that works on desktop and mobile. The trick was getting it to work on iPhone.
Setting preload=metadata works on desktop and android devices but not iPhone.
For iPhones I had to set it to autoplay so the poster image automatically appears on initial load. iPhones will prevent the video from auto playing, but the poster image appears as the result.
I had to do a check for iPhone using Pavan's answer found here. Detect iPhone Browser. Then use the proper video tag with or without autoplay depending on the device.
var agent = navigator.userAgent;
var isIphone = ((agent.indexOf('iPhone') != -1) || (agent.indexOf('iPod') != -1)) ;
$videoTag = "";
if(isIphone()) {
$videoTag = '<video controls autoplay preload="metadata">';
} else {
$videoTag = '<video controls preload="metadata">';
}
You can set preload='auto' on the video element to load the first frame of the video automatically.
Solution for #2, #3 etc. frames. We need attach disposable handler .one() for resetting default frame.
<video width="300" height="150" id='my-video'>
<source src="testvideo.mp4#t=2" type="video/mp4" />
</video>
$(function () {
let videoJs = videojs('my-video');
videoJs.one('play', function () {
this.currentTime(0);
});
});
I found a great way to dynamically add poster to a video!
To show the desired frame from video (in my case it's the frame at 1.75 seconds) - add preload="metadata" to the video element and #t=1.75 to the end of source URL.
Add eventListener to the video element that will listen for play event only once.
Once the event is emitted reset the video time.
<video width="100%" controls="controls" preload="metadata" id="myVid">
<source src="path/to/your/video#t=1.75" type="video/mp4">
</video>
<script>
var el = document.getElementById('myVid');
el.addEventListener('play', () => {
el.currentTime = 0;
}, { once: true });
</script>

Categories

Resources