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

How to Dynamically Change Navbar Color on Scroll?

Linda Hamilton
Release: 2024-12-17 17:32:10
Original
782 people have browsed it

How to Dynamically Change Navbar Color on Scroll?

Dynamic Navbar Color Change While Scrolling

Achieving a navbar with no background color initially and progressively changing its color after scrolling requires a combination of JavaScript and CSS modifications.

JavaScript:

$(function () {
  $(document).scroll(function () {
    var $nav = $(".navbar-fixed-top");
    $nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
  });
});
Copy after login

This code checks for the vertical scroll position of the document. If it exceeds the height of the navbar, it toggles a class "scrolled" to the navbar element.

CSS:

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

This CSS code defines the appearance of the navbar with the "scrolled" class. It applies a white background color and a smooth transition effect while changing the color.

Implementation:

By adding the provided JavaScript code to the head of your HTML document and the CSS code to your style sheet, you can easily implement this dynamic navbar color change. When the user scrolls down the page, the navbar will gradually transition to the desired background color.

Reference:

For a live demonstration, refer to the following JSFiddle: [JSFiddle](https://jsfiddle.net/qe9L725y/).

The above is the detailed content of How to Dynamically Change Navbar 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