简体   繁体   中英

jQuery - scroll or jump to top

The context: I have a one page web app. So there's lots of div 's being hidden at any one time (I'm not sure if this matters). What I am finding is that when a user is finished with one page (Page X), then they click back (to Page Y) - if they return back to Page X then the position is the same as when they left the page. The back button is at the bottom, so that's where the user ends up again.

What I want, is when they return to Page X for them to be at the top of the page so they can start again. Whether it scrolls back or just jumps back - either way is fine.

I've tried all of the following with no success:

    // Scroll to top
    setTimeout(function(){
        alert('scroll');
        $('html, body').animate({scrollTop : 0}, 2000);
    }, 2000);

Adding a div with the id top-anchor at the top and using:

    $('html, body').animate({
       scrollTop: $("#top-anchor").offset().top
    }, 2000);

Having a and using an anchor, with the code below (it only works once though, after that as the hash is already in the URL it no longer works I suppose):

document.hash = '#top-anchor';

Also tried:

window.scrollTo(0, 0);

No luck.

Any alternative ideas are much appreciated.

You can achieve something like that: DEMO : https://jsfiddle.net/yeyene/bpwtLg1w/1/

Not sure how your content divs are shown and hidden, but just get the idea of adding scroll to top of page div part.

Add scroll event on Back button click event, since you already known which page to go, you can scroll to this page's top, by using...

$(element).position().top

JQUERY

$(document).ready(function () {
    $('input[type=button]').on('click', function(){
        getPageID = $(this).attr('id');

        $('.page').hide(0);
        $('div#'+getPageID).show(0);

        $('html,body').animate({
            scrollTop: $('div#'+getPageID).position().top - 10
        }, 500);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM