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

How to Change Navbar Background Color on Scroll?

Linda Hamilton
Release: 2024-11-26 10:24:18
Original
219 people have browsed it

How to Change Navbar Background Color on Scroll?

Modifying Navbar Color Post-Scroll

Question:

How can you remove the background color from a navbar initially and then add a new color once scrolling occurs?

Scenario:

The website in question, https://attafothman.olympe.in/, features a black navbar at the top that should maintain a fixed position. However, when scrolling down below a certain div, the navbar automatically acquires a new background color.

Solution:

To address this issue, a combination of JavaScript and CSS is employed.

JavaScript:

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

This JavaScript code triggers an event listener on scroll. When the scroll position exceeds the height of the navbar, it adds a custom CSS class named 'scrolled' to the element.

CSS:

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

This CSS rule defines the behavior of the 'scrolled' class. It assigns a solid white background color to the element with the 'navbar-fixed-top' class once it has the 'scrolled' class added. The '!important' keyword ensures that this rule overrides any conflicting styles.

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