Тег button, атрибут formtarget

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:

Источник

Атрибут formtarget

Определяет окно или фрейм в которое будет загружаться результат, возвращаемый обработчиком формы, в виде HTML-документа.

Синтаксис

   

Значения

В качестве значения используется имя окна или фрейма, заданное атрибутом name . Если установлено несуществующее имя, то будет открыто новое окно. В качестве зарезервированных имен можно указывать следующие.

_blank Загружает страницу в новое окно браузера. _self Загружает страницу в текущее окно. _parent Загружает страницу во фрейм-родитель, если фреймов нет, то это значение работает как _self . _top Отменяет все фреймы и загружает страницу в полном окне браузера, если фреймов нет, то это значение работает как _self .

       

Ваше имя:

Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.

Типы тегов

HTML5

Блочные элементы

Строчные элементы

Универсальные элементы

Нестандартные теги

Осуждаемые теги

Видео

Документ

Звук

Изображения

Объекты

Скрипты

Списки

Ссылки

Таблицы

Текст

Форматирование

Формы

Фреймы

Источник

How to Make an Unobtrusive Scroll-to-Top Button

A button to return to the top of the page allows the user to quickly return to the top of the page without making too much effort. This can be very useful when the page has a lot of content or which happens, for example, on one page websites, when infinite scrolling is used, or on mobile devices where different screen sizes can cause the content to scroll extend. Those buttons usually float in the bottom corner of sites and then take you back to the top of the page when clicked. They are pretty easy to create with JavaScript. But visually, we are looking for it to be non-obtrusive while still being a large enough target to tap or click. Let’s look at a few ways we can do this, starting simple, then improving things as we go.

var scrollToTopBtn = document.getElementById("scrollToTopBtn")

Now document.documentElement returns the root element of the document. We need it to get the offset values. So, next let’s save it in a variable called rootElement — that way it’s easier to call in the code.

var rootElement = document.documentElement
function scrollToTop < // scroll to top logic >scrollToTopBtn.addEventListener("click", scrollToTop)

Then, inside the scrollToTop function, we will make it scroll to the top of the screen with the scrollTo method.

Option 2: Detecting the scroll position

function handleScroll() < // Do something on scroll >document.addEventListener("scroll", handleScroll)
  • scrollHeight gives the height of an element, including the part not visible due to overflow.
  • clientHeight gives the inner height of an element in pixels, which is the height of the visible part.

If we subtract scrollHeight by clientHeight , we get the total amount of pixels that we can scroll:

var scrollTotal = rootElement.scrollHeight - rootElement.clientHeight

Now we have a variable called scrollTotal that represents the maximum number of pixels that can be scrolled vertically. By dividing the amount scrolled by the total amount of pixels we can scroll, we get a ratio between 0 and 1. Playing with this ratio, we can easily toggle the button on and off.

For example, we will add a condition that shows the scroll-to-top button when the user has scrolled 80%, (or a ratio of 0.80) down the total height of the page. 80% is an arbitrary number. Basically, the closer we get to 1, the more the user has to scroll before seeing the button.

var rootElement = document.documentElement function handleScroll() < // Do something on scroll var scrollTotal = rootElement.scrollHeight - rootElement.clientHeight if ((rootElement.scrollTop / scrollTotal ) >0.80 ) < // Show button scrollToTopBtn.classList.add("showBtn") >else < // Hide button scrollToTopBtn.classList.remove("showBtn") >> document.addEventListener("scroll", handleScroll)

We’re going to want some CSS to position the button correctly when it comes into view:

With that, the button appears when the user gets 80% down the page and then hides when it’s higher than that.

This seems like a grand option, and setting an event listener to do this is pretty easy. But the performance overhead can be costly since we’re always checking the current scroll position.

There’s another option that takes care of this…

Option 3: Intersection Observer

The Intersection Observer API is an excellent solution to the above problem. It’s a fairly recent browser API that lets developers hand most of these tasks off to the browser, in a way that is more optimized. Travis Almand wrote up a thorough explanation of how it works. Here’s how MDN defines it:

The Intersection Observer API provides a way to asynchronously observe changes for the intersection of a target element with an ancestor element or with a top-level document’s viewport.

Pretty neat! That means the button can be our target element:

// We select the element we want to target var target = document.querySelector("footer");

We then write a callback function that does something when our element becomes “intersects” with the viewport — which is a fancy way of saying when it comes into view.

And once the footer enters or leaves the viewport, all we really want to do is add or remove a class. The callback receives an array of entries as a parameter.

function callback(entries, observer) < // The callback will return an array of entries, even if you are only observing a single item entries.forEach(entry => < if (entry.isIntersecting) < // Show button scrollToTopBtn.classList.add('showBtn') >else < // Hide button scrollToTopBtn.classList.remove('showBtn') >>); >

We need to create a new IntersectionObserver instance and pass it the callback function we just wrote.

let observer = new IntersectionObserver(callback);

Finally, we tell the observer to start watching (err, observing) the target element that was selected above for when it intersects with the viewport:

And what about smooth scrolling?

Of course it’s possible! In fact, Chris showed us how it can be done with CSS back in 2019:

There’s a little more nuance to there, like accessibility enhancements that Chris also covers in the post. The point is that CSS is gaining new powers that can accomplish things that we used to use JavaScript for.

There you have it! We started with a pretty simple idea. We enhanced it by displaying and hiding the button based on the user’s scroll position. Then we improved the performance by implementing the Intersection Observer API instead of watching the current scroll position. And, finally, we saw how CSS can be used for smooth scrolling. All together, we get a scroll-to-top button that is easy to see and use, while not blocking other elements on the page.

Источник

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 */
>

#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
>

Источник

Читайте также:  Virtualenv python 3 windows создать виртуальную среду
Оцените статью