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?
You can calculate the
offset
of the element and then compare that with thescroll
value like: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:
Demo Fiddle
You can use jQuery plugin with the
inview
event like this :Link : https://remysharp.com/2009/01/26/element-in-view-event-plugin
Combining this question with the best answer from jQuery trigger action when a user scrolls past a certain part of the page
UPDATE
I've improved the code so that it will trigger when the element is half way up the screen rather than at the very top. It will also trigger the code if the user hits the bottom of the screen and the function hasn't fired yet.
This should be what you need.
Javascript:
CSS:
HTML:
Check this bootply: http://www.bootply.com/atin_agarwal2/cJBywxX5Qp