my goal is when the video enters the viewport the video will play automatic even is not clicked in the play button and auto-pause when leaves the viewport even is not clicked in pause button
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video id="video1" played="false" style="width: 100%; height: 60vh" controls controlslist="nodownload">
<source src="assets\homevideo.mp4" type="video/mp4">
<source src="assets\homevideo.ogg" type="video/ogg">
</video>
<script>
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
setInterval(function() {
$('video').each(function(){
let id = $(this).attr("id");
let played = $(this).attr("played");
if ($(this).isInViewport()) {
if (played == "false") {
$(this)[0].play();
$(this).attr("played", "true");
}
} else {
if (played == "true") {
$(this)[0].pause();
$(this).attr("played", "false");
}
}
});
}, 1000);</script>