facebook-squared twitter-squared rss-squared gplus-squared

Scroll to the Top of the page

Written by on 17 January 2016

Sunday

17

January 2016

0

COMMENTS

Scroll to Top

Lately I visited E-commerce website and while I was surfing through there book section, I got lost. In few minutes I was no where and was desperate to find a place to start. It was even intimidating to scroll to the top of the page every time, although I know home key or scroll bar would take me there, and I din’t wanted to leave mouse or search for Home key on the keyboard.

That said, and as an Impatient person on the world being a web visitor I wanted to show you how to create one of those scroll to top button.

Nitty-Gritty:

These buttons are normal anchor tags which points the browser some where top of the page. Best place is the logo of the website. As logo of the website is already linked to the main page, just add and ID element and use it withe the href attribute down below of the anchor tag. Put this code down some where in the footer or where it’s usable.

<div class="go-top">
    <a href="#logo">Go to Top</a>
</div>

Above in the “ref” attribute, we are using # or ampersand just before the logo to internally link the web page. Now if you implement it, it would jump back to the top of the page or ( where is your logo). This action will abrupt. If you want to make this scrolling a bit smoother, carry on your reading.

Scroll de animate

We will be needing a little bit of jQuery to animate the entire page to go to the top of the page. Following code also provided as a github gist too.

$(".go-top").on('click','a',function  (event) {
        event.preventDefault();
        var elAttr = $(this).attr('href');
        $('body,html').animate({
        scrollTop: $(elAttr).offset().top
    },700);
});

Here on second line we are disabling default behavior of links, so that we could define custom behavior to it. Next we are grabbing whatever is in the href attribute of our scroll-to-top link.┬áIn the third line we are using animate function of jquery to animate entire page to the target element – in our case it’s the website logo.

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: