0

I want the page to scroll to the top if its on a certain page of my app.

It needs to do this after the page has been shown.

I'm using the code:

$('.current-page, #'+desiredPage).toggleClass('current-page')

if(desiredPage === 'page-search-results'){

    $(window).scrollTop(scrollPosition)

}else{

    $(window).scrollTop(0)

}

however, the page scrolls to the top a split second before the class is actually toggled (the class has the css in it to show the page). Why is this? and how to make sure it only happens after?

This is only noticeable on mobile.

as per the comments/ answer i tried using:

$('.current-page, #'+desiredPage).toggleClass('current-page').promise().done(function(){

    if(desiredPage === 'page-search-results'){

        $(window).scrollTop(scrollPosition)

    }else{

        $(window).scrollTop(0)

    }

});

but it still happens?

rpsep2
  • 3,061
  • 10
  • 39
  • 52
  • Check out the answer on this question: http://stackoverflow.com/questions/10321393/jquery-function-on-toggleclass-complete. It suggests using `promise()` to make sure that `toggleClass` has completed. You could try using this, and then once it is completed, call `scrollTop`. – lhan Aug 27 '13 at 13:27
  • Possible duplicate http://stackoverflow.com/questions/10321393/jquery-function-on-toggleclass-complete – Mark Walters Aug 27 '13 at 13:31
  • That is not a duplicate, In this case there is no duration or animation, therefore there is no need for a callback. What's happening is the scroll is happening before the render finishes. The only thing i can think of is to use a very short setTimeout. – Kevin B Aug 27 '13 at 14:41

1 Answers1

0

If you add a return false; at the end of the function (i.e. after the if/else clauses) it might solve the problem?

I've been wrestling with a similar problem, and found the hint at the bottom of this article:

http://chris-spittles.co.uk/jquery-smooth-page-scrolling/

It says there,

Returning false simply prevents the browser carrying out its default behaviour

For me, and in the example given on the page that means that the anchor does not jump down to the page before the animation, although, since your not using anchors, but toggling classes, I'm not quite sure what the "default behaviour" is in this case.

Hope it helps.