I want to start a function when a div is scrolled into the viewport. My problem is, that the function is triggered/started again every time I continue to scroll.
HTML:
<div class="box"></div>
JS:
$(document).ready(function() {
function start() {
alert("hello");
}
$(window).scroll(function() {
if ( $(window).scrollTop() >= $('.box').offset().top - ($(window).height() / 2)) {
$(".box").addClass("green");
start();
} else {
$(".box").removeClass("green");
}
});
});
To sum up: the function "start" should be started, when the div is scrolled into the viewport. But it should be not triggered again, after it was triggered once.
You can setup a flag like:
var started = false;
function start() {
if(!started) {
alert("hello");
}
started = true;
}
$(document).ready(function() { var started = 0; function start() { if(started==0) { alert("Alert only once"); } started = 1; } $(window).scroll(function() { if ( $(window).scrollTop() >= $('.box').offset().top - ($(window).height() / 2)) { $(".box").addClass("green"); start(); } else { $(".box").removeClass("green"); } }); });
*{margin:0;} .box { background: red; height: 200px; width: 100%; margin: 800px 0 800px 0; } .green { background: green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <br /> <center> <br /> <h1>scroll down</h1> </center> <div class="box"></div>
There's a bunch of ways to go about this. You could just remove the event listener (since you're using jQuery, I'll use the on
and off
methods):
$(window).on('scroll', function() {
if ( $(window).scrollTop() >= $('.box').offset().top - ($(window).height() / 2)) {
$(".box").addClass("green");
start();
} else {
$(".box").removeClass("green");
}
$(window).off('scroll');
});
if you want window scroll method to stop once the start method meet its requirement.. you can do it this way
$(document).ready(function() {
var toggleScroll = false;
function start() {
alert("hello");
}
$(window).one("scroll", checkToggleScroll);
function checkToggleScroll(){
if ( $(window).scrollTop() >= $('.box').offset().top - ($(window).height() / 2)) {
$(".box").addClass("green");
toggleScroll = true;
start();
} else {
$(".box").removeClass("green");
}
if(!toggleScroll){
$(window).one("scroll", checkToggleScroll);
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.