Sticky div with JavaScript: How to keep a div fixed to the top on scroll

If you want to keep a div fixed to the top of the page while scrolling, you can achieve this by using JavaScript. The process involves attaching an event listener to the window object that triggers a function whenever the user scrolls. In this function, you can check the current scroll position and compare it to the position of the div you want to stick to the top. If the user has scrolled past the div, you can add a CSS class to the div that fixes its position to the top.

To implement this functionality, you can use the following code:


window.addEventListener('scroll', function() {
  var div = document.querySelector('.sticky-div');
  var divPosition = div.getBoundingClientRect().top;
  var scrollPosition = window.pageYOffset || document.documentElement.scrollTop;

  if (scrollPosition >= divPosition) {
    div.classList.add('fixed-top');
  } else {
    div.classList.remove('fixed-top');
  }
});

In this code, we first select the div we want to make sticky using the querySelector method. We then get the position of the div relative to the viewport using the getBoundingClientRect method. Finally, we check the current scroll position of the page using the window.pageYOffset or document.documentElement.scrollTop properties.

If the user has scrolled past the div, we add a CSS class called fixed-top to the div using the classList.add method. This class should contain the necessary CSS rules to fix the div to the top of the page. If the user scrolls back up, we remove the fixed-top class using the classList.remove method.

By implementing this code, you can create a div that stays fixed to the top of the page while the user scrolls, improving the user experience and making your website more engaging.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

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

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information