How to Maintain Active Navigation State in Bootstrap CSS Without Default Background Colors?

Linda Hamilton
Release: 2024-10-27 00:43:02
Original
381 people have browsed it

How to Maintain Active Navigation State in Bootstrap CSS Without Default Background Colors?

Bootstrap CSS: Maintaining Active Navigation

Bootstrap provides a navigation system that allows users to easily navigate through different sections of a website. However, sometimes it is desired to customize the menu without the default background colors. In such cases, it may be necessary to implement additional logic to maintain the active navigation state when scrolling or clicking on menu items.

Consider the following scenario: a custom menu has been created using HTML and CSS, similar to the subnav menu on the Bootstrap website. However, the active class does not switch when scrolling down or clicking on the menu items.

HTML:

<code class="html"><ul class="menu">
    <li><a href="#" aria-current="page">Home</a></li>
    <li><a href="#about">About Us</a></li>
    <li><a href="#contact">Contact</a></li>
</ul></code>
Copy after login

CSS:

<code class="css">.menu {
  list-style:none;
}
.menu > li {
  float: left;
}
.menu > li > a {
  color: #555;
  float: none;
  padding: 10px 16px 11px;
  display: block;
}
.menu > li > a:hover {
  color: #F95700;
}
.menu a[aria-current="page"],
.menu a[aria-current="page"]:hover {
  color:#F95700;
}</code>
Copy after login

To fix this issue, additional JavaScript is required. The following jQuery code clears the active class from all menu items before adding it to the current item:

JavaScript:

<code class="js">$('.navbar li').click(function(e) {
    $('.navbar li.active').removeClass('active');
    var $this = $(this);
    if (!$this.hasClass('active')) {
        $this.addClass('active');
    }
    e.preventDefault();
});</code>
Copy after login

By incorporating this code, the active class will now switch correctly when navigating through the menu. This solution allows for a customized navigation system that maintains the desired visual behavior.

The above is the detailed content of How to Maintain Active Navigation State in Bootstrap CSS Without Default Background Colors?. 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