Juju
Juju

Reputation: 3

Adjust scroll position to a nearest container

I currently looking for a JavaScript (Jquery lib for example) solution to adjust the position of the scroll to a specific css class. The goal is to reposition the scroll bar on the nearest container.

As this website : http://www.takumitaniguchi.com/tokyoblue/

Thank JUJU

Upvotes: 0

Views: 1936

Answers (1)

Luka
Luka

Reputation: 341

if you use JQuery something like that is relatively easy to achieve if i understand your question correctly. Heres roughly how i would do it:

function scrollTo(a){
    //Get current scroll position
    var current = (document.all ? document.scrollTop : window.pageYOffset);
    //Define variables for data collection
    var target = undefined;
    var targetpos = undefined;
    var dif = 0;
    //check each selected element to see witch is closest
    $(a).each(function(){
        //Save the position of the element to avoid repeated property lookup
        var t = $(this).position().top;
        //check if there is an element to check against
        if (target != undefined){
            //save the difference between the current element's position and the current scroll position to avoid repeated calculations
            var tdif = Math.abs(current - t);
            //check if its closer than the selected element
            if(tdif < dif){
                //set the current element to be selected
                target = this;
                targetpos = t;
                dif = tdif;
            }
        } else {
            //set the current element to be selected
            target = this;
            targetpos = t;
            dif = Math.abs(current - t);
        }
    });
    //check if an element has been selected
    if (target != undefined){
        //animate scroll to the elements position
        $('html,body').animate({scrollTop: targetpos}, 2000);
    }
}

This might not be the best way to do it, but it should work. Just call the function and pass a JQuery selection as the first argument.

Upvotes: 4

Related Questions