We recently launched a new website, and it is sort of using the large-scale design mindset that you are seeing a lot nowadays. With a vertical nav that allows you to scroll up/down the page depending on which section you click. I needed the vertical nav to change “selected” based on which section you are in as you scroll up/down the page. So I came up with this quick and handy piece of code. I’ve found that the code is proving more useful in other areas of use as well!

Trigger events based on the position of the scrollbar (i.e. the visibility of elements on the page as they are scrolled into/out of view).

To use:

*Include jQuery and scrollToggle.js (link to download via GitHub)

[sourcecode lang=”javascript”]

//ScrollToggle(verticalScrollTriggerPosition, callbackScrolledTO, callbackScrolledAWAY)

//verticalScrollTriggerPosition can be a number, property, or computed. It is the vertical Y coord of the scrollbar destination.

var myScroller = new ScrollToggle($(‘#block1’).position().top, function () {

console.log(“Element has been reached.”);

}, function () {

console.log(“Element is gone.”);



A few things to note:

  1. The code is designed so that the moment a DOM element passes the very bottom of the screen, the event is triggered.  This is considered “visible”.  If you prefer, you can change the logic so that the event is triggered the moment the DOM element hits the very copy of the screen.  The sample code page below has examples for both scenarios.

A complete working example can be found here: http://kroltech.com/upload/misc/scrollToggle_Sample/

A better production sample can be found here: http://www.nextgenugm.com (the orange dots in the right vertical nav change based on the sections as they scroll into view).