Home > Web Front-end > CSS Tutorial > How Can I Highlight the Current Page Link in a Navigation Menu Using CSS and jQuery?

How Can I Highlight the Current Page Link in a Navigation Menu Using CSS and jQuery?

Barbara Streisand
Release: 2024-12-31 04:21:18
Original
1038 people have browsed it

How Can I Highlight the Current Page Link in a Navigation Menu Using CSS and jQuery?

How to Change Link Color for the Current Page Using CSS and jQuery

Problem:

How can I change the text and background colors of a link to highlight the current page in a navigation menu?

CSS Solution:

For basic styling, CSS provides the li a selector to target all links inside list items:

li a {
  color: #A60500;
}

li a:hover {
  color: #640200;
  background-color: #000000;
}
Copy after login

However, this approach does not distinguish the current page link.

jQuery Solution:

To dynamically highlight the current page link, jQuery's .each function can be used:

$(document).ready(function() {
    $("[href]").each(function() {
        if (this.href == window.location.href) {
            $(this).addClass("active");
        }
    });
});
Copy after login

This code iterates through all links, checks if their href matches the current page URL, and adds the "active" class to match the predefined styles.

Considerations:

  • Narrow down the link selection using CSS selectors like $("nav [href]").
  • Handle URL parameters by stripping them with this.href.split("?")[0].
  • This approach allows you to avoid manual changes on each page and maintain consistency in the link styling.

The above is the detailed content of How Can I Highlight the Current Page Link in a Navigation Menu Using CSS and jQuery?. 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