Scroll back to the top of div javascript w3schools năm 2024

Hey! Before you go too far down the rabbit hole of JavaScript-based smooth scrolling, know that there is a native CSS feature for this: scroll-behavior.

html {
  scroll-behavior: smooth;
}

And before you reach for a library like jQuery to help, there is also a native JavaScript version of smooth scrolling, like this:

// Scroll to specific values
// scrollTo is the same
window.scroll({
  top: 2500, 
  left: 0, 
  behavior: 'smooth'
});
// Scroll certain amounts from current position 
window.scrollBy({ 
  top: 100, // could be negative value
  left: 0, 
  behavior: 'smooth' 
});
// Scroll to a certain element
document.querySelector('.hello').scrollIntoView({ 
  behavior: 'smooth' 
});

Dustan Kasten has a polyfill for this. And you’d probably only reach for this if you were doing something with scrolling the page that couldn’t be done with

target jump links and CSS.

Accessibility of Smooth Scrolling

Whatever technology you use for smooth scrolling, accessibility is a concern. For example, if you click a `

hash` link, the native behavior is for the browser to change focus to the element matching that ID. The page may scroll, but the scrolling is a side effect of the focus changing.

If you override the default focus-changing behavior (which you have to, to prevent instant scrolling and enable smooth scrolling), you need to handle the focus-changing yourself.

Heather Migliorisi wrote about this, with code solutions, in Smooth Scrolling and Accessibility.

Smooth Scroll with jQuery

jQuery can also do this. Here’s the code to perform a smooth page scroll to an anchor on the same page. It has some logic built in to identify those jump links, and not target other links.

// Select all links with hashes
$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="
# 0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
      && 
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });

If you’ve used this code and you’re all like HEY WHAT’S WITH THE BLUE OUTLINES?!, read the stuff about accessibility above.

James Quick has a nice step-by-step tutorial on how to implement smooth scrolling in React using the react-scroll plugin:

Example

Get the offsetTop position of "myDIV":

const element = document.getElementById("myDIV"); let pos = element.offsetTop;

Try it Yourself »

Get the positions of "myDIV":

const element = document.getElementById("test"); Let pos1 = element.offsetTop; let pos2 = element.offsetLeft;

Try it Yourself »

More examples below.


Description

The offsetTop property returns the top position (in pixels) relative to the parent.

The returned value includes:

  • the top position, and margin of the element
  • the top padding, scrollbar and border of the parent

The offsetTop property is read-only.



Syntax

Return the top offset position:

Return Value

Type Description NumberThe top position of the element, in pixels.


More Examples

Create a sticky navigation bar:

// Get the navbar const navbar = document.getElementById("navbar");

// Get the offset position of the navbar const sticky = navbar.offsetTop;

// Add the sticky class to the navbar when you reach its scroll position. Remove the sticky class when you leave the scroll position. function myFunction() { if (window.pageYOffset >= sticky) { navbar.classList.add("sticky") } else { navbar.classList.remove("sticky"); } }

Try it Yourself »


Browser Support

element.offsetTop is supported in all browsers:

Chrome Edge Firefox Safari Opera IE Yes Yes Yes Yes Yes Yes


★ +1

W3schools Pathfinder

Track your progress - it's free!

How to scrollTo top of div in JavaScript?

In the click listener, we call div. scroll with an object with top set to 0 to scroll to the top. And behavior is set to 'smooth' to add smooth scrolling.

How to scroll back to top JavaScript?

Setting the position parameter to 0 scrolls the page to the top. Syntax: $(window).

How do you get the scroll top in JavaScript?

You can use element. scrollTop and element. scrollLeft to get the vertical and horizontal offset, respectively, that has been scrolled. element can be document.

How do you scrollTo the beginning of an element in JavaScript?

To scroll to the very beginning, we can use scrollTo(0,0) .