最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trigger function only once on scroll - Stack Overflow

programmeradmin1浏览0评论

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.

Fiddle

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.

Fiddle

Share Improve this question asked Sep 16, 2019 at 17:16 Maximilian NeuseMaximilian Neuse 1631 gold badge5 silver badges15 bronze badges 2
  • 2 what about a variable as a flag, that is setted to true inside start(), then inside the scroll() you check if this flag is false before run start()? – Calvin Nunes Commented Sep 16, 2019 at 17:19
  • my final fiddle: jsfiddle/eu8ab9Lq/1 – Maximilian Neuse Commented Sep 17, 2019 at 5:31
Add a ment  | 

5 Answers 5

Reset to default 6

You can setup a flag like:

var started = false;
function start() {
  if(!started) {
    alert("hello");
  }
  started = true;
}

Demo

  $(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./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);
        }
    }

  });

Just run the start() function when the $(".box) doesn't have the class "green" (that is added after a certain amount of scroll).

$(document).ready(function() {

  function start() {
    alert("hello");
  }

  $(window).scroll(function() {
    if ($(window).scrollTop() >= $('.box').offset().top - ($(window).height() / 2)) {
      if (!$(".box").hasClass("green")) {
        $(".box").addClass("green");
        start();
      }
    } else {
      $(".box").removeClass("green");
    }
  });
});
.box {
  background: red;
  height: 200px;
  width: 100%;
  margin: 800px 0 800px 0;
}

.green {
  background: green;
}
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box"></div>

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>