Skip to content
Advertisement

How to change appearance of “position: sticky” element ONLY when the user starts scrolling and its stickiness becomes apparent?

I have some very simple CSS code that makes one particular div container “sticky”, and when the user scrolls down, that div element stays locked at the top of the screen as expected.

I am trying to figure out how to make it so the sticky element in question CHANGES APPEARANCE the instant the user scrolls down and the “stickiness” of this element becomes clear? Maybe when it hits the top of the parent container, maybe just when the user scrolls past a certain point — there might be several ways to code this, but I can’t seem to figure out any.

Specifically what I want to do is — add a bottom border of 1px when they start scrolling and the sticky element follows. Until then, have the border be invisible/not there.

Note also that I read borders cause weird problems with sticky elements, and that shadows are a workaround for this, so I’m currently doing this for the “border”:

box-shadow: inset 0 0px 0 #000000, inset 0 -1px 0 #000000;

Thanks!

Advertisement

Answer

Simply put your style in a class and toggle this class in your HTML

//Simply with jQuery
$(window).scroll(function () {
   if ($(this).scrollTop() > 150) {
      $('.element').addClass('your_class_name');
   } else {
      $('.element').removeClass('your_class_name');
   }
});

//With JavaScript
window.onscroll = function() {
if (document.body.scrollTop > 150 || document.documentElement.scrollTop > 150) {
    document.querySelector(".element").classList.add("your_class_name");
  } else {
    document.querySelector(".element").classList.remove("your_class_name");
  }
};

This will add class if user scrolled over 150px

Advertisement