JQuery - Event triggered by div position

JQuery - Event triggered by div position

Hi all

Is it possible to use JQuery to trigger an event from the position of a div in relation to the browser window.

I have this demo page here that contains three div’s positioned below each other

http://www.ttmt.org.uk/forum/7_scroll/

When I scroll down the page I want an alert to say “Div one in view”, “Div two in view” etc. I know more than one div could be visible in the browser window but I wanted it to alert the one in the centre of the window.

I was thinking it would be best to fire an event when the div is a set distance from the top of the browser window - I don’t know where to start with it, or if using the distance from the top of the browser is the best way.

The “firing” bit should be done using window.onscroll, although beware of what it might do (so use one of the solutions mentioned there, like a timeout).

Then you need to work out which one is more “central”. How you determine that depends on the size of the divs and the size of the browser window. However, you can write some code that can work it out based on the distance from the top of the viewport (that’s the metric I’d use).

To calculate the distance from the top of the viewport, you need two things: the distance between the top of the page and the DIV, and how far you’ve scrolled. Those properties will be theDiv.offsetTop and window.scrollTop.

Be careful with offsetTop though, because the offsetParent might not be the document (or body). So you may need to also check the offsetParent’s offsetTop and iterate until you reach the top.