Trigger event when user scroll to specific element - with jQuery

后端 未结 12 1362
攒了一身酷
攒了一身酷 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:39

    You can calculate the offset of the element and then compare that with the scroll value like:

    $(window).scroll(function() {
       var hT = $('#scroll-to').offset().top,
           hH = $('#scroll-to').outerHeight(),
           wH = $(window).height(),
           wS = $(this).scrollTop();
       if (wS > (hT+hH-wH)){
           console.log('H1 on the view!');
       }
    });
    

    Check this Demo Fiddle


    Updated Demo Fiddle no alert -- instead FadeIn() the element


    Updated code to check if the element is inside the viewport or not. Thus this works whether you are scrolling up or down adding some rules to the if statement:

       if (wS > (hT+hH-wH) && (hT > wS) && (wS+wH > hT+hH)){
           //Do something
       }
    

    Demo Fiddle

提交回复
热议问题