Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  157] [ 3]  / answers: 1 / hits: 18397  / 10 Years ago, tue, march 4, 2014, 12:00:00

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...


More From » jquery

 Answers
51

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.


[#72163] Monday, March 3, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradley

Total Points: 555
Total Questions: 102
Total Answers: 99

Location: Tajikistan
Member since Fri, Nov 27, 2020
4 Years ago
;