Question

I'm trying to build a function like this one:

var t =$('#top');
var q1=$('#fe1');
var q2=$('#fe2');
var q3=$('#fe3');
var q4=$('#fe4');
var q5=$('#fe5');
var win = $(window);
var doc=$(document);
var wins = win.scrollTop();
var docs = doc.scrollTop();


function next (){
    if (wins == docs) {
        q1.ScrollTo();
    }
    else if (wins == q1.scrollTop()) {
        q2.ScrollTo();
    }
    else if (wins == q2.scrollTop()) {
            q3.ScrollTo();
    }
    else if (wins == q3.scrollTop()) {
        q4.ScrollTo();
    }
    else if (wins == q4.scrollTop()) {
        q5.ScrollTo();
    }
}

I want to go scrolling to the next section. To do so, the code checks in which section I am so it knows which section to scroll to. But I think $(window).scrollTop() is not what I am looking for.

I want a statement that returns the distance between the top of the page and the top of what I am displaying. Maybe i have to do a more complex operation. Do you know how can i get this?

Thanks.

Was it helpful?

Solution

This problem is quite simple to solve even without jQuery or similar in plain JavaScript. Here it is for your example:

var next = (function (sections) {

    function getTop(node) {
        return node ? node.offsetTop + getTop(node.offsetParent) : 0;
    }

    return function () {
        var i, nodeTop, top = window.pageYOffset;

        for (i = 0; i < sections.length; i += 1) {
            nodeTop = getTop(document.getElementById(sections[i]));
            if (nodeTop > top) {
                window.scrollTo(window.pageXOffset, nodeTop);
                return;
            }
        }
    };
}(['top', 'fe1', 'fe2', 'fe3', 'fe4', 'fe5']));

The code is quite general, so you can pass any section ids you want (they just need to appear in the correct order).

We use two standard DOM properties/functions here window.pageYOffset and window.scrollTo() to get and set vertical offset of the window (window.pageXOffset is used to keep horizontal offset the same). To get the vertical offset of the section start I defined getTop function using simple recursion (jQuery uses similar code IMHO).

Resulting function next() is defined in a self-invoking closure to hide the implementation and helper function. To use it after this code is run, you simply call

next();

I tested this code, so I am quite confident it works :).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top