How to scroll to an element with jQuery ?

To scroll to a specific element using jQuery, you can use the .animate() method with the scrollTop property. Here’s how to do it:

Basic Scroll to Element

$('html, body').animate({
    scrollTop: $('#target-element').offset().top
}, 1000); // 1000ms (1 second) animation duration

Step-by-Step Explanation

  1. Target the Element
    Use a jQuery selector to get your target element:
   const $target = $('#target-element');
  1. Calculate Position
    Get the element’s top position relative to the document:
   const targetPosition = $target.offset().top;
  1. Animate Scroll
    Animate the scrollTop property of the html/body elements:
   $('html, body').animate({
       scrollTop: targetPosition
   }, 1000); // Duration in milliseconds

Full Example

$('#scroll-button').click(() => {
    const $target = $('#section-2');
    $('html, body').animate({
        scrollTop: $target.offset().top
    }, 500); // Smooth 500ms scroll
});

Optional Customizations

1. Offset (e.g., for fixed headers)

Subtract the height of a fixed header to avoid overlap:

const headerHeight = $('.fixed-header').outerHeight();
const targetPosition = $target.offset().top - headerHeight;

2. Horizontal Scroll

Use scrollLeft for horizontal scrolling:

$('html, body').animate({
    scrollLeft: $('#target-element').offset().left
}, 1000);

3. Instant Scroll (No Animation)

$('html, body').scrollTop($target.offset().top);

Scroll Inside a Container

For scrolling within a <div> (instead of the window):

const $container = $('#scroll-container');
const targetPosition = $target.position().top; // Position relative to container

$container.animate({
    scrollTop: targetPosition
}, 1000);

Notes

  • .offset() returns the element’s position relative to the document.
  • .position() returns the position relative to the parent.
  • Always target both html and body for cross-browser compatibility.

Leave a Reply

Your email address will not be published. Required fields are marked *