
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;
}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");
}
});
});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:
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!