Toggle CSS on scroll

Tell at what pixel from the top the CSS should be triggered, in this example i’m targeting the navbar with id=”topnav”. You also need JQuery for this to work.

<script>
$(document).ready(function(){
  $(window).scroll(function(){
    var scroll = $(window).scrollTop();
      if (scroll > 100) {
        $("#topnav").css("transition" , "background-color 1.5s ease");
        $("#topnav").css("background" , "black");
      } else {
        $("#topnav").css("background" , "transparent");
      }
  })
})
</script>

You could use .addClass and .removeClass instead of .css

$("#topnav").addClass("bg-gray");

Leave a comment

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