user3685048 user3685048 - 3 months ago 11
Javascript Question

Stopping a scrollhandler from running after someone clicks an element

Ok so when someone scrolls to the video it starts and when someone scrolls away from the video it stops using load restarting the video and showing the poster.

The problem I have is that I don't want this function to run when someone clicks to pause the video. It would be pretty annoying for the scroll handler to take control.

jQuery(window).load(function(){
jQuery(window).scroll(function(){
playvideo();
});
});
var playvideo = function(){
var scrollTop = jQuery(window).scrollTop()+jQuery(window).height();
var elem='.video';
var video = document.getElementById('video-background');
var elheight = jQuery(elem).height();
if(scrollTop >= jQuery(elem).offset().top+elheight){
//fade out the video play button and start the video
$j('.video-caption-wrapper').fadeOut("Fast",function() {video.play();});
}else{
// fade in the play button and reload the video
$j('.video-caption-wrapper').fadeIn("Fast",function() {video.load()});

}
}
$j('#video-background').click(function(event) {
//when the video is clicked pause it and unbind scrolling
if (this.paused == false) {
this.pause();
$j(window).off("scroll",playvideo);
} else {
this.play();
}
});

Answer

This:

jQuery(window).load(function(){
    jQuery(window).scroll(function(){
        playvideo();
    });
});

Should be:

jQuery(window).load(function(){
    jQuery(window).scroll(playvideo);
});

That will allow you to refer to the playvideo function when removing the scroll listener. Right now you try to remove playvideo as a listener when you have never added it. You added an anonymous function which calls playvideo.

Comments