Home > Web Front-end > CSS Tutorial > How to Achieve Active Navigation in Bootstrap Menus with Custom CSS and JavaScript?

How to Achieve Active Navigation in Bootstrap Menus with Custom CSS and JavaScript?

Barbara Streisand
Release: 2024-11-01 05:42:02
Original
848 people have browsed it

How to Achieve Active Navigation in Bootstrap Menus with Custom CSS and JavaScript?

Achieving Active Navigation with Bootstrap CSS

Creating customized navigation menus in Bootstrap while maintaining the active class functionality can be a challenge. This article addresses the issue of why the active class does not switch when scrolling or clicking on menu items.

HTML Structure

The provided HTML essentially comprises a list of items with corresponding anchors:

<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

Custom CSS

The CSS styles for the menu define basic properties such as list styling, float, and padding. Additionally, hover states and active states are specified:

<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

JavaScript for Active State

To correctly switch the active class, JavaScript is required. The following snippet handles clicks on menu items and ensures that only one item is active at a time:

<code class="javascript">$('.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

Additional Considerations

In this specific case, the Bootstrap navigation, represented by .navbar in the JavaScript, is being targeted. However, it is always important to consider the specifics of your implementation when adapting this solution.

By utilizing the provided HTML, CSS, and JavaScript, you can achieve a customized navigation menu with the desired active class functionality.

The above is the detailed content of How to Achieve Active Navigation in Bootstrap Menus with Custom CSS and JavaScript?. 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