How to know which div is displayed on the screen with javascript?

0

I have a website with several divs, and I need it when the screen arrives on a given div, an action happens, but I do not know which javascript or jquery event is responsible for that.

Example:

<div id='1'>
  div1
</div>
<div id='2'>
  div2
</div>

Thanks for the help.

    
asked by anonymous 05.09.2016 / 20:20

1 answer

2

As I've been working a lot with scrolling in the last few days, I was at my fingertips, here's a simple example: just implement control variables to check if the action has already been triggered and avoid repetition ...

// armazena o scrolltop do elemento que deseja aguardar
var scrollTopoffset = $('#dois').offset().top - $(window).height();

$(window).scroll(function() {
  if ($(window).scrollTop() > scrollTopoffset) {
  // rolagem chegou ao elemento
    alert('#dois apareceu!');
  }
});
#um {
  background-color: #ddd;
  height: 500px
}
#dois {
  background-color: #eee;
  height: 500px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='um'>
  div1
</div>
<div id='dois'>
  div2
</div>
    
05.09.2016 / 22:29