How to implement a button that scrolls to the top of the page using jQuery (Javascript)

How to implement a button that scrolls to the top of the page using jQuery (Javascript)

Hello, this is naouniverse ( @naouniverse708 ).

I was implementing a button to scroll to the top of the page using jQuery (Javascript), but there were some pages that didn't work properly due to a writing error, so I recreated it.

Below is a memo on how to implement it.

Design buttons with HTML and CSS

For the HTML part, write the following in the body.

<a style="display: block;" class="pagetop" href="#top">↑ Page Top ↑</a>

href specifies any location.

Then, design the button using CSS.
I made it feel simple and easy to understand.
I think it's okay to keep the key points in check and tweak things to your liking.

.pagetop{ background-color:rgba(255,0,0,0.8); border-radius:5px; color:#ffffff; padding:8px; position:fixed; /* Fixed display location */ bottom:80px; right :0px; font-family: 'Roboto Condensed', sans-serif; text-decoration: none; z-index: 100; /* Avoid going below */ } /* Change color on hover */ .pagetop :hover{ background-color:rgba(0,0,255,0.8); }

Loading jQuery files hosted on Google

Write the following in the head.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

Control events with jQuery

Write the following in head or create an external js file with the following content and load it.

<script type="text/javascript"> jQuery(function(jQuery) { var pagetop = jQuery('.pagetop'); pagetop.hide(); /* 最初は非表示 */ /* ページスクロール時 */ jQuery(window).scroll(function () { if (jQuery(this).scrollTop() > 100) { pagetop.fadeIn(); /* 表示 */ } else { pagetop.fadeOut(); /* 非表示 */ } }); /* ボタンクリック時 */ pagetop.click(function () { jQuery('body, html').animate({ scrollTop: 0 }, 500); return false; }); }); </script>

Afterword

I rewrote the whole thing this time, but it was a good thing because it was relatively easy to rewrite.

Please note that this button is not implemented on smartphone pages.
I felt that it would get in the way due to the page design, and there is another reason.

For more information, please refer to the [Related] article below.

[Related]: Tap the iPhone status bar to scroll to the top of the page

  • Add this entry to Hatena Bookmarks

At "naouniverse.com", the administrator writes about things, things, and the world that interest him.
Gadgets, cameras, design, programming, L'Arc~en~Ciel, etc...