Home > Web Front-end > CSS Tutorial > How Can I Change My Navbar\'s Background Color on Scroll?

How Can I Change My Navbar\'s Background Color on Scroll?

Barbara Streisand
Release: 2024-11-30 11:36:10
Original
1001 people have browsed it

How Can I Change My Navbar's Background Color on Scroll?

Dynamic Nav-Bar Color Change on Scrolling

Enhance your website's navigation experience by transforming the nav-bar color as you scroll down the page. In this question, the user sought guidance to remove the background color of the nav-bar initially and then apply a color when scrolling past a specific div.

Solution:

The solution involves a combination of JavaScript and CSS. First, add the following JavaScript code to your HTML document's head section:

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

This JavaScript code monitors the window's scroll position and toggles the "scrolled" class on the nav-bar when the scroll exceeds the nav-bar's height.

Next, add the following CSS code to your stylesheet:

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

This CSS ensures that when the "scrolled" class is applied to the nav-bar, its background color changes to white (#fff) with a smooth transition over 200 milliseconds.

By implementing this solution, you can create a dynamic navigation bar that enhances the user experience by providing a visual cue as they scroll through the page's content.

The above is the detailed content of How Can I Change My Navbar\'s Background 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