Caspert Caspert - 4 months ago 7
Javascript Question

Issue with play video once on scroll?

I use the following code to play a video if the section

#user-experience
is reached on scroll:

JS:

var player = $('video');

function isInView(elem){
return $(elem).offset().top - $(window).scrollTop() < $(elem).height();
}

$(window).scroll(function() {

if (isInView($('#user-experience'))) {
// console.log('play video');
player.get(0).play();
}

});


HTML:

<video>
<source src="images/browser.webm" type="video/webm">
<source src="images/browser.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>


The problem with the code is that it will fire the script every time the user scrolls a little bit, until the section is not visible in the browser viewport. The code should only fire once if the user scrolled to the
#user-experience
section. When scroll to another section and back, the video should not play for the second time.

How do I fix this?

Answer

Like this?

var player = $('video');
var hasReachedUserExperience = false;

function isInView(elem){
    return $(elem).offset().top - $(window).scrollTop() < $(elem).height();
}

$(window).scroll(function() {

    if (isInView($('#user-experience')) && !hasReachedUserExperience) {
        hasReachedUserExperience = true;
        player.get(0).play();
    }

});

A simple boolean flag seems to meet your behavior requirements.