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);
}
}
UPDATE:
The additional function I added in the ajax call success workers like a charm for me. The only issue I have now is in the 3rd Code Snippet listed above, there is a Boolean attribute { once: true}
attached to the event listener that only fires and calls the function once.
If I remove the Boolean attribute the event listener fires on each click or touch start event and continuously calls the function assigned.
I need the event listener to fire once and only call the assigned function once "after each ajax call"