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

Asked

Viewed 1,054 times

0

I have a site with multiple Ivs, and I need that when the screen arrives in a certain div, an action happens, but I don’t know which javascript event or jquery is responsible for it.

Example:

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

I appreciate the help.

  • Try to detail better what you want to do.

1 answer

2

As I am working a lot with scroll in the last few days, was at my fingertips, follows below a simple example, just implement control variables to check if the action has already been fired 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>

Browser other questions tagged

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