I am using ajax to append videos elements to a webpage. After a new video is appended, I noticed that some JavaScript & jQuery are not initializing.
There are 3 code snippets that I need to work together.
1st. Code Snippet for Ajax call
2nd. Code Snippet That Unmutes Video after it is played
3rd. Code Snippet plays video after first initial click or touch gesture anywhere on webpage.
*1st Code Snippet = The following code snippet is used to Append Videos via Ajax Calls after the user scrolls the page.
**
var step = 1;
var loading = false;
$(window).scroll(function(){
if ($(window).scrollTop() >= $(document).height()-$(window).height()-1900){
if(loading === false){
loading = true;
$.ajax({
url: 'HTTPS://ENTER URL HERE.COM'+step,
success: function (data) { step++; $('main2').append(data); loading = false; },
dataType: 'html'
});
}
}
});
I want the appended video to automatically start playing after the webpage is clicked or touched and for the video to unmute after it starts playing.
I’ve tried minor tweaks but have not been successful at getting this to work with "videos appended via ajax", however these codes work perfectly together when the video is already on the page during the initial load.
I need both of the code snippets below to work after ajax.
2nd Code Snippet ( Used to unmute html video with autoplay attribute after it starts)
$("video").on('play',function(){
$("video").prop('muted', false);
});
$("video").on('pause',function(){
$("video").prop('muted', true);
});
$("video").on('ended',function(){
$("video").prop('muted', true);
});
3rd Code Snippet ( Used to Play Html Videos on webpage with a click or touch gesture. )
Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
get: function () {
return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
}
});
document.body.addEventListener("click", playVideoOnLowPower, { once: true });
document.body.addEventListener("touchstart", playVideoOnLowPower, { once: true });
function playVideoOnLowPower(){
try{
const videoElements = document.querySelectorAll("video");
for (i = 0; i < videoElements.length; i++) {
if (videoElements[i].playing) {
// video is already playing so do nothing
console.log('Playing');
}
else {
// video is not playing so play video now
videoElements[i].play();
console.log('Not Playing');
}
}
}
catch(err) {
console.log(err);
}
}
2
Answers
Since, you bind the video via ajax, but in your ajax success you just bind the video to
$('main2')
and you haven’t re-bind an event to it. It will not have the event listeners automatically that you bind previously. So, you need to rebind the event after your$('main2').append(data);
in ajax success.$('main2')
is not a valid selector unless you have a<main2>
tag