Trigger event when user scroll to specific element - with jQuery

后端 未结 12 1497
攒了一身酷
攒了一身酷 2020-11-22 11:52

I have an h1 that is far down a page..

TRIGGER EVENT WHEN SCROLLED TO.

and I want to trigger an alert

12条回答
  •  醉话见心
    2020-11-22 12:54

    Just a quick modification to DaniP's answer, for anyone dealing with elements that can sometimes extend beyond the bounds of the device's viewport.

    Added just a slight conditional - In the case of elements that are bigger than the viewport, the element will be revealed once it's top half has completely filled the viewport.

    function elementInView(el) {
      // The vertical distance between the top of the page and the top of the element.
      var elementOffset = $(el).offset().top;
      // The height of the element, including padding and borders.
      var elementOuterHeight = $(el).outerHeight();
      // Height of the window without margins, padding, borders.
      var windowHeight = $(window).height();
      // The vertical distance between the top of the page and the top of the viewport.
      var scrollOffset = $(this).scrollTop();
    
      if (elementOuterHeight < windowHeight) {
        // Element is smaller than viewport.
        if (scrollOffset > (elementOffset + elementOuterHeight - windowHeight)) {
          // Element is completely inside viewport, reveal the element!
          return true;
        }
      } else {
        // Element is larger than the viewport, handle visibility differently.
        // Consider it visible as soon as it's top half has filled the viewport.
        if (scrollOffset > elementOffset) {
          // The top of the viewport has touched the top of the element, reveal the element!
          return true;
        }
      }
      return false;
    }
    

提交回复
热议问题