How to Dynamically Change Navigation Bar Color on Scroll?

Linda Hamilton
Release: 2024-11-28 03:04:11
Original
549 people have browsed it

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());
      });
    });
    Copy after login
  2. Add CSS to Style the Navigation Bar:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template