简体   繁体   中英

Show div when class appears on screen

So far I had this function which works:

var offsetTop = $(".card").offset().top;

$(window).scroll(function(){
  var scrollTop = $(window).scrollTop();
  if(scrollTop > offsetTop){
    $(".popupcorner").fadeIn(200);
  }
});

I need small change. I want .popupcorner to appear once .card is visible on screen, in bottom.

I believe what you want is to reveal the .popupcorner as soon as the card is visible from the bottom. If so, then the function getBoundingClientRect can come in handy. It gives you the position of an element relative to the viewport.

var rect = $(".card")[0].getBoundingClientRect()
// if element's top is "above" the bottom of the screen
if(rect.top < window.innerHeight){
    $(".popupcorner").fadeIn(200);
}

You can use Intersection Observer for this if your browser support allows for it, since it's more performant than a scroll listener. When used with the default options it'll fire as soon as 1px of the target element comes into view.

let observer = new IntersectionObserver(function(entries, observer) {
  // Callback will fire once when we set it up, so we check if the element 
  // is actually in the viewport.
  if (entries.filter((entry) => entry.isIntersecting).length != 0) {
    $('.popupcorner').fadeIn();
    // Once the element is in view, work is done. Dispose of the observer.
    observer.disconnect();
  }
});

observer.observe($('.card')[0]);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM