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?
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.
You could use this for all devices,
I use the same code doing that all the time, so added a simple jquery plugin doing it. 480 bytes long, and fast. Only bound elements analyzed in runtime.
https://www.npmjs.com/package/jquery-on-scrolled-to
It will be
$('#scroll-to').onScrolledTo(0, function() { alert('you have scrolled to the h1!'); });
or use 0.5 instead of 0 if need to alert when half of the h1 shown.
I think your best bet would be to leverage an existing library that does that very thing:
http://imakewebthings.com/jquery-waypoints/
You can add listeners to your elements that will fire off when your element hits the top of the viewport:
For an amazing demo of it in use:
http://tympanus.net/codrops/2013/07/16/on-scroll-header-effects/
Inview library triggered event and works well with jquery 1.8 and higher! https://github.com/protonet/jquery.inview
Read this https://remysharp.com/2009/01/26/element-in-view-event-plugin
If you are doing a lot of functionality based on scroll position, Scroll magic (http://scrollmagic.io/) is built entirely for this purpose.
It makes it easy to trigger JS based on when the user reaches certain elements when scrolling. It also integrates with the GSAP animation engine (https://greensock.com/) which is great for parallax scrolling websites