user2252219
user2252219

Reputation: 865

Adjust scroll position to a nearest wrapper div both upwards and downwards

I've read a bunch of threads but still can't come away with a solution that doesn't use a snap scroll plugin (https://github.com/wtm/jquery.snapscroll).

I was trying to follow this

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);
}

}

I'm trying to get it to scroll into view

<div class="projectWrap"> 

Fiddle: http://jsfiddle.net/Dar_T/2h2wjp2L/1/

much like how this site http://www.takumitaniguchi.com/tokyoblue/ has it scroll for its containers.

Upvotes: 0

Views: 539

Answers (2)

AlexJaa
AlexJaa

Reputation: 389

First you have to find the offset() of the element. Then comparing it to the $(window.scrollTop()), then you can do whatever changes you want. Here's some of the codes:

var project1 = $(".projectWrap").offset();
if($(window).scrollTop() >= project1.top){ // compare window scrolltop to element offset()
    $("#tlos1").css("color","blue"); // change navigation
    $("#tlos2").css("color","black");
    $("#tlos3").css("color","black");
}

Here's the DEMO

Upvotes: 1

Kamil
Kamil

Reputation: 1030

Try this out:

var topoffset = 30;
function goTo(tagId) {
    var destination = $( '#'+tagId ).offset().top - topoffset;
    $("html:not(:animated),body:not(:animated)").animate( { scrollTop: destination}, speed);
});

And create urls with hash like this:

<a href="javascript:goTo('myTagId');">Go to section1</a>

Upvotes: 0

Related Questions