Trigger event when user scroll to specific element - with jQuery

Karl Coelho picture Karl Coelho · Feb 4, 2014 · Viewed 220.7k times · Source

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

<h1 id="scroll-to">TRIGGER EVENT WHEN SCROLLED TO.</h1>

and I want to trigger an alert when the user scrolls to the h1, or has it in it's browser's view.

$('#scroll-to').scroll(function() {
     alert('you have scrolled to the h1!');
});

how do I do this?

Answer

DaniP picture DaniP · Feb 4, 2014

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