Execute function when arriving in Div

Asked

Viewed 1,219 times

0

There is how to perform a function only when a div is on the user screen?

Example, I have a div that is in the middle of the site and when user scrolls up to it, or get to it, I want a function to be executed.

There are ways to do this with Angularjs or Jquery?

2 answers

1

The example below has the div #box hidden with opacity:0, when you reach the scroll in the middle of the div #box I change the opacity to 1;

var executou = false;
  $(document).scroll(function() {
      if (!executou && $(window).scrollTop() > $('#box').offset().top/2) {
          $('#box').css('opacity','1');
          executou = true;
      }
  });
#base{
  min-height:600px
}

#box{
transition:1s;
min-height:300px;
margin-top:100%;
background:red;
opacity:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="base">
  <div id="box">
  </div>
</div>

0

That one reply of Soen serves you:

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
       alert("near bottom!");
   }
});

-100 is the value for height that will trigger the event.

Fiddle for Nick Craver

Browser other questions tagged

You are not signed in. Login or sign up in order to post.