Samuel Bolduc
Samuel Bolduc

Reputation: 19173

scrollTop going back top before scrolling

I have a function which scrolls the page to a given offset. I'm using the parallax effect, so all my elements (and pages, or "slides") are positioned depending on the scroll bar location.

My little problem is that when I click a link to another slide, it scrolls the page to the desired offset, but the event binded is triggered. Which should be OK, to keep the smooth effect. But there's a little glitch, it seems that the scrollTop function goes back to top for a millisecond before executing correctly. So it lookes like theres another page displaying for a millisecond every time I click on a link before scrolling to the right place.

Here is my code:

    for(var i=1;i<8;i++)
    {
        (function(slideNum) {
            var tempName = 'slide'+slideNum;
            //console.log(defaultPositions["slide"+i].top);
            $('a.slide'+i).bind('click', function() {
                $.scrollTo((defaultPositions[tempName].top/slidesScrollSpeed)+1+'px', 800);
            });
        })(i);
    }

I know it might be hard to find the problem in this code, but it's all I could find that is related to that. Do you know what's wrong?

Thanks!

PS: scrollTo is a jQuery plugin but has the same glitch as scrollTop...

Upvotes: 1

Views: 1008

Answers (1)

MrOBrian
MrOBrian

Reputation: 2189

You need to prevent the default action of the links. I'm assuming you have something like href="#" on your links? Change your click binding to:

$('a.slide'+slideNum).bind('click', function(event) {
    event.preventDefault();
    $.scrollTo((defaultPositions[tempName].top/slidesScrollSpeed)+1+'px', 800);
});

Edit: I noticed you pass in i as slideNum but then use i, so I changed my code to use the passed in value stored in slideNum

Upvotes: 5

Related Questions