I have a website that has multiple videos on a page. The number of videos varies by user. I would like all videos to autoplay when the user accesses the page. This is doable on desktop and iOS browsers. However, many Android browsers require a workaround for autoplay. See my code:
<?php
for ($i=0; $i < $videos.length; $i++) {
?>
<video playsinline autoplay muted loop>
<source class="img-responsive center-block col-md-7" src="<?php echo ${'videos' . $i} ?>" type="video/mp4">
Your browser does not support the video tag.
</video>
<?php
}
?>
<script>
var video = document.querySelector('video');
window.addEventListener('touchstart', function videoStart() {
video.play();
console.log('first touch');
// remove from the window and call the function we are removing
this.removeEventListener('touchstart', videoStart);
});
</script>
I have tried both querySelector
and querySelectorAll
. querySelector('video')
obviously works for selecting the 1st video, but none of the following. querySelectorAll('video')
does not select any videos.
Are there any alternatives to querySelector
that would work?
I have a website that has multiple videos on a page. The number of videos varies by user. I would like all videos to autoplay when the user accesses the page. This is doable on desktop and iOS browsers. However, many Android browsers require a workaround for autoplay. See my code:
<?php
for ($i=0; $i < $videos.length; $i++) {
?>
<video playsinline autoplay muted loop>
<source class="img-responsive center-block col-md-7" src="<?php echo ${'videos' . $i} ?>" type="video/mp4">
Your browser does not support the video tag.
</video>
<?php
}
?>
<script>
var video = document.querySelector('video');
window.addEventListener('touchstart', function videoStart() {
video.play();
console.log('first touch');
// remove from the window and call the function we are removing
this.removeEventListener('touchstart', videoStart);
});
</script>
I have tried both querySelector
and querySelectorAll
. querySelector('video')
obviously works for selecting the 1st video, but none of the following. querySelectorAll('video')
does not select any videos.
Are there any alternatives to querySelector
that would work?
2 Answers
Reset to default 6you can try
var videoList = document.getElementsByTagName("video");
this will return all the video tags from your page
Thanks !
HTML5 video "autoplay" property should work with most browsers. You might wanna look at Video Browser Compatibility, autoplay is on the second row.
To enable autoplay for all the videos on a page check out the code below:
<script>
var videos = document.querySelectorAll('video'); // get all videos using "video" css selector
/*Loop*/
for(video of videos) { // use var video if "strict mode" is enabled
video.addEventListener('loadstart', function() { // during the loading process
video.autoplay = true; // set autoplay proterty to true
})
video.load(); // now reload
}
</script>