Home >Web Front-end >CSS Tutorial >How to Dynamically Change Navigation Bar Color on Scroll?

How to Dynamically Change Navigation Bar Color on Scroll?

Linda Hamilton
Linda HamiltonOriginal
2024-11-28 03:04:11574browse

How to Dynamically Change Navigation Bar Color on Scroll?

How to Change Navigation Bar Color When Scrolling

Problem:

Setting a transparent background color for the navigation bar doesn't work when the page is scrolled, resulting in a new background color being applied.

Solution:

To change the navigation bar color after scrolling, follow these steps:

  1. Add JavaScript to the Head:

    $(function () {
      $(document).scroll(function () {
        var $nav = $(".navbar-fixed-top");
        $nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
      });
    });
  2. Add CSS to Style the Navigation Bar:

    .navbar-fixed-top.scrolled {
      background-color: #fff !important;
      transition: background-color 200ms linear;
    }

Implementation:

The JavaScript code watches for page scrolling. Once the scroll exceeds the height of the navigation bar, it adds a class named scrolled to the navigation bar. The CSS code styles the navigation bar with a white background color when the scrolled class is present. This transitions the background color smoothly over 200 milliseconds.

This solution allows you to set a transparent background color for the navigation bar when it's not scrolled and change the background color to white when scrolling occurs.

The above is the detailed content of How to Dynamically Change Navigation Bar Color on Scroll?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn