Html click on top

JavaScript — bring div element to front on click

In this article, we would like to show you how to bring div element to the front on click event using JavaScript.

  1. create three div elements,
  2. create global counter variable to store value for z-index property,
  3. add event listeners that listen for click events the the div elements,
  4. click handler functions increment the global counter and set z-index property of the clicked div element to the new counter value so it moves to the front.
// ONLINE-RUNNER:browser;    body < height: 200px; >div < position: absolute; height: 100px; width: 100px; border: 3px solid gray; >#red < background: #ff6666; border: 3px solid #ff3333; top: 90px; left: 40px; >#green < background: #00cc00; border: 3px solid #009e00; top: 40px; left: 70px; >#blue 

Click on the div to bring it to the top

Reusable code example

// ONLINE-RUNNER:browser;    body < height: 200px; >div < position: absolute; height: 100px; width: 100px; border: 3px solid gray; >#red < background: #ff6666; border: 3px solid #ff3333; top: 90px; left: 40px; >#green < background: #00cc00; border: 3px solid #009e00; top: 40px; left: 70px; >#blue 

Click on the div to bring it to the top

Alternative titles

Источник

How TO — Scroll Back To Top Button

Learn how to create a «scroll back to top» button with CSS.

How To Create a Scroll To Top Button

Step 1) Add HTML:

Create a button that will take the user to the top of the page when clicked on:

Example

Step 2) Add CSS:

Example

#myBtn <
display: none; /* Hidden by default */
position: fixed; /* Fixed/sticky position */
bottom: 20px; /* Place the button at the bottom of the page */
right: 30px; /* Place the button 30px from the right */
z-index: 99; /* Make sure it does not overlap */
border: none; /* Remove borders */
outline: none; /* Remove outline */
background-color: red; /* Set a background color */
color: white; /* Text color */
cursor: pointer; /* Add a mouse pointer on hover */
padding: 15px; /* Some padding */
border-radius: 10px; /* Rounded corners */
font-size: 18px; /* Increase font size */
>

Читайте также:  Java для сенсорных дисплеев

#myBtn:hover background-color: #555; /* Add a dark-grey background on hover */
>

Step 3) Add JavaScript:

Example

// Get the button:
let mybutton = document.getElementById(«myBtn»);

// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() ;

function scrollFunction() if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) mybutton.style.display = «block»;
> else mybutton.style.display = «none»;
>
>

// When the user clicks on the button, scroll to the top of the document
function topFunction() document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
>

Источник

Scroll-to-top Button in vanilla JS (Beginners)

Scroll to top button is a very common UX feature in websites. It’s goal is to prevent annoying users forced to scroll back up — especially on mobile devices. In this short tutorial, we’ll see how to implement one with css and pure (vanilla) javascript. The simplest way to get a scroll to top button is to have an html element at the top and a link near the end of your page that calls it:

html  scroll-behavior: "smooth"; > 

That’s the easiest way to get a scroll to top (I’ve actually missed this on my original post as Loouis Low pointed out in the comments.) Result here: No javascript needed!

Scroll to top button with vanilla js

  • Show button after the user has scrolled down x % of the page.
  • Animate entrance and leave.

The button

Let’s just created a simple button with a class of scrollToTopBtn so we can refer to it in js.

Here are a few CSS properties for the button:

  • position: fixed; gets it out of the flow of the page.
  • bottom: 50px; and right: 50px; places it at the bottom right corner.
  • z-index: 100; a large z-index keeps the button on top of every other elements.
  • display: none; is used to hide it at first.

Detect user scroll

we can detect user’s scroll with a scroll event listener:

document.addEventListener("scroll", handleScroll); function handleScroll()  // do something on scroll > 

Show the Scroll to Top button logic

In the handleScroll function, we’ll check whether we need to show or hide the button. We are going to use three element properties:

  • clientHeight gives us the visible part of an element in its parent.
  • scrollHeight gives the total height of an element including the overflow part.

The height of the overflow part is the total amount of pixels that can be scrolled. In other words: scrollableHeight = scrollHeight — clientHeight

var scrollableHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight; 

document.documentElement is the document element. We are using it instead of document because scrollHeight and clientHeight are elements’ properties.

  • scrollTop gives the number of pixels scrolled from the top. It’s the amount of pixels scrolled by the user.

By dividing scrollTop with scrollableHeight we get a ratio between 0 and 1. 0 meaning the user hasn’t scrolled and 1 meaning the user scrolled to the end of the page. This ratio tells us how much the user scrolled.

If we want the scroll to top button to show up after the user scrolled 50% we set a golden ratio of 0.5. And, with an if else statement, make the button visible above and hidden below.

document.addEventListener("scroll", handleScroll); // get a reference to the button var scrollToTopBtn = document.querySelector(".scrollToTopBtn"); function handleScroll()  var scrollableHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight; var GOLDEN_RATIO = 0.5; if ((document.documentElement.scrollTop / scrollableHeight ) > GOLDEN_RATIO)  //show button scrollToTopBtn.style.display = "block"; > else  //hide button scrollToTopBtn.style.display = "none"; > > 

With that the scroll-to-top button appears and hides on scroll.

Scroll to top

There a lot of scrolling examples that use jQuery. But these days it is really easy to do this in pure js with scrollTo:

\\. scrollToTopBtn.addEventListener("click", scrollToTop); function scrollToTop()  window.scrollTo( top: 0, behavior: "smooth" >); > 
  • top: 0, means scroll to 0px vertically.
  • behavior: «smooth» makes the scroll smooth.
  • there’s also a left property for horizontal scroll.

And that’s it! Here’s the final js:

document.addEventListener("scroll", handleScroll); // get a reference to our predefined button var scrollToTopBtn = document.querySelector(".scrollToTopBtn"); function handleScroll()  var scrollableHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight; var GOLDEN_RATIO = 0.5; if ((document.documentElement.scrollTop / scrollableHeight ) > GOLDEN_RATIO)  //show button scrollToTopBtn.style.display = "block"; > else  //hide button scrollToTopBtn.style.display = "none"; > > scrollToTopBtn.addEventListener("click", scrollToTop); function scrollToTop()  window.scrollTo( top: 0, behavior: "smooth" >); > 

Tada 🎉🎉🎉!

Thanks for reading 🥰🥰!! I hope this was of help.

Improvements:

I’ve tried to keep it simple. Usually I would also toggle a class instead of the display to show a transition animation.

Here’s how you could fade up the button:

Источник

Very Simple HTML Scroll To Top Button (Free Download)

Welcome to a quick tutorial on how to create a simple HTML scroll to top button. There are a ton of scroll-to-top plugins all over the Internet, but know what? Forget those overly complicated ones. We don’t even need to load an entire library just to create a “back to top” button.

To create an easy HTML scroll to top button without Javascript:

Yes, that’s all. But let us walk through a better example in this guide – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

TLDR – QUICK SLIDES

Simple HTML Scroll To Top Button

TABLE OF CONTENTS

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

BACK TO TOP

All right, let us now get into the example of how to create a “back to top” button – With pure HTML CSS Javascript.

1) THE HTML

Just an image button. Yep, that’s all.

2) FIXED BUTTON ON THE CORNER

#backtop < /* (A) BOTTOM RIGHT CORNER */ position: fixed; bottom: 20px; right: 20px; z-index: 999; /* (B) HIDDEN BY DEFAULT */ visibility: none; opacity: 0; /* (C) COSMETICS */ cursor: pointer; transition: opacity 0.3s; >/* (D) SHOW BUTTON */ #backtop.show
  1. position: fixed; bottom: X; right: X; will fix the button at the lower right corner, regardless of the scrolling.
  2. visibility: none; opacity: 0; Hide the button by default.
  3. Well, just a bit of cosmetics.
  4. .show < visibility: visible; opacity: 1; >The idea is to attach this CSS class to the button when the user has scrolled down sufficiently, this will show the button; When the user is back at the top, we remove this CSS class to hide the button.

3) JAVASCRIPT

// (A) SMOOTH SCROLL TO TOP const totop = () => window.scroll(< top: 0, left: 0, behavior: "smooth" >); // (B) SHOW/HIDE BUTTON const togtop = () => < if (window.scrollY >= 100) < document.getElementById("backtop").classList.add("show"); >else < document.getElementById("backtop").classList.remove("show"); >>; window.addEventListener("scroll", togtop); window.addEventListener("resize", togtop);
  1. Fired when we click on the “back to top” button, smooth scroll to the top of the page.
  2. Sadly, CSS cannot detect scrolling at the time of writing. So we will use window.scrollY to detect the scrolling, add/remove the show CSS class to show/hide the “back to top” button accordingly.

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “Very Simple HTML Scroll To Top Button (Free Download)”

Simple and nicely working solution. Exactly what I was looking for. Thanks a lot!

Leave a Comment Cancel Reply

Breakthrough Javascript

Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

Socials

About Me

W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

Источник

Оцените статью