Can you identify the selected item on the menu?

My goal is to highlight the menu item for the current page by adding a "current" class. I've tried several code snippets from this website, but most of them didn't work as expected. The code I'm currently using almost works, but it has a small issue where the Home button is always highlighted along with the current page's menu item. For example, when viewing the "Archive" page, both Archive and Home buttons are highlighted.

Just so you know, I am using Wordpress to build my website and I know that Wordpress supports this effect. However, I would like to achieve this without relying on Wordpress.

This is the HTML code:

<ul class="navigation">
 <li><a href="<?php echo home_url() ?>" class="navItem">Home</a></li>
 <li><a href="<?php echo home_url(/archive) ?>" class="navItem">Archive</a></li>
 <li><a href="<?php echo home_url(/about) ?>" class="navItem">About</a></li>
</ul>

And here is the JS code:

jQuery(function($) {
        $('.navigation li a').each(function() {
            var target = $(this).attr('href');
            if(location.href.match(target)) {
                $(this).addClass('current');
            } else {
                $(this).removeClass('current');
            }
    });
});

I must admit that I'm not very familiar with javascript, so there could be some mistakes in the code.

Thank you for taking the time to read this, and I wish you a fantastic new year!

Answer №1

When working with WordPress, the recommended approach is to use wp_nav_menu, but if you're in need of a quick fix and don't anticipate frequent changes to the menu, you can implement a check within each list item.

<ul class="navigation">
 <li><a href="<?php echo home_url() ?>" class="navItem <?php if( is_front_page() ): echo 'current'; endif; ?>">Home</a></li>
 <li><a href="<?php echo home_url(/archive) ?>" class="navItem <?php if( is_home() || is_archive() || is_single() ): echo 'current'; endif; ?>">Archive</a></li>
 <li><a href="<?php echo home_url(/about) ?>" class="navItem <?php if( is_page('About') ): echo 'current'; endif; ?>">About</a></li>
</ul>

This method relies on utilizing WordPress' "Conditional Tags" which return either "true" or "false" based on the page being viewed. It's important to note that the second link checks for multiple blog/post conditions (assuming it's for the blog).

Answer №2

Not sure if this information will be helpful to you. For those using wordpress, you can customize your menu like so:

<?php
   wp_nav_menu(array(
       'theme_location' => 'header',
     'menu_class' => 'navbar-nav px-0',
      'depth' => 2,
   'container' => false,
   ));

?> and when landing on the current page, wordpress automatically includes aria-current="page" to your 'nav-link'. You can then style the current page with CSS in this way:

ul.navbar-nav [aria-current]:not([aria-current="false"])

If there are 'sub-menus', wordpress adds a '.sub-menu' class to the ul child elements, allowing you to customize them further.

ul.navbar-nav li ul.sub-menu [aria-current]:not([aria-current="false"])

You can view my previous website for reference:

Answer №3

One method that can be used is implementing a basic filter to add a current class to a link in the navigation menu.

add_filter('nav_menu_link_attributes', 'add_current_class_to_link', 10, 4);
function add_current_class_to_link($atts, $item, $args, $depth)
{
    $atts['class'] = $item->current ? 'current' : '';
    return $atts;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Facebook's UI share URL parameters within the Facebook app on mobile devices

Encountering an issue with the Fb ui share functionality on certain smartphones Here is the function: function shareFB(data){ FB.ui({ method: 'share', href: data, }, function(response){}); } Implemented as follows: $urlcod ...

Discover how to effortlessly unveil JSON data by clicking on data retrieved from an API

After successfully parsing data from a Tumblr API, I encountered an issue when introducing tags within the body description, which includes images and hyperlinks. The main task at hand is to create a list of blog titles where the corresponding blog descri ...

Creating a custom design for legends in Chart.js

I'm currently working on a project using chart.js and I'm trying to customize the label/legend styling for my chart. My goal is to replace the rectangular legend with a circular one. I've come across the suggestion of creating a custom legen ...

The main content will be displayed on the sub-routes of the child

I'm feeling uncertain about the routes for children. For example, I have an 'About' route with 'me' as a sub-route: { path: '/about', name: 'About', component: About, children: [ { ...

How to transform an image into a base64 string using Vue

I am having trouble converting a local image to base64. The function reader.readAsDataURL is not working for me. Instead of the image data, I always get 'undefined' assigned to the rawImg variable. The file variable contains metadata from the upl ...

The function app.post in Express Node is not recognized

I decided to organize my routes by creating a new folder called 'routes' and moving all of them out of server.js. In this process, I created a file named 'apis.js' inside the routes folder. However, upon doing so, I encountered an error ...

Enhancing HTML Layouts using Visual Basic for Applications

I'm currently experiencing some difficulties when embedding HTML into VBA to send an email. The formatting is not appearing as intended, and I've been experimenting with different options. My first concern is regarding the font size displayed in ...

The functionality of the combobox in Vuetify differs from that of an input field

I have implemented Vuetify and am using its combobox component for search functionality on my website. However, I have noticed that the text value in the combobox only gets added to the watcher when the mouse exits the field. This behavior is not ideal f ...

Multiple variable evaluation in Javascript does not function properly

Currently, I have an array that I am looping through in order to create variables. The variable names are derived from the array itself and I am using eval (only on my local machine) to achieve this. Interestingly, I can successfully create a variable and ...

"Hiding elements with display: none still occupies space on the

For some reason, my Pagination nav is set to display:none but causing an empty space where it shouldn't be. Even after trying overflow:hidden, visibility:none, height:0, the issue persists. I suspect it might have something to do with relative and ab ...

Switching visual representation that appears upon clicking the dropdown menu

Issue with Duplicating Dropdown and Image Change const image = document.querySelector('.item__img'); const checkbox = document.querySelectorAll('.imgOption'); function handleChange() { let imgsrc = this.getAttribute("data-value ...

Utilize jQuery and HTML simplistically to display or conceal divs throughout a webpage

After developing some basic jQuery code using if-statements to toggle the visibility of Divs based on a select list in HTML, I am seeking ways to enhance this code: 1) How can I achieve the same functionality with fewer lines of code? 2) Rather than manu ...

Leveraging an external React library to utilize .ogg files for audio playback specifically in the Safari

Hey there! I'm currently working on incorporating ogg-opus audio playback in a react app on Safari (since it doesn't support .ogg format). My project was initialized using create-react-app. I came across the "ogv.js" library, which supposedly h ...

Modifying the CSS design of specific columns within a table created using JavaScript

A unique way to showcase JSON data in a table is by utilizing a for loop within a function. This method, however, does not assign an ID or Class to the table. To hide the final three columns of this table using CSS, the following code can be employed (whe ...

Unexpected behavior in AJAX call

I'm currently working on implementing an AJAX call to display a partial view once a radio button is selected. Despite following the recommendations found on Stack Overflow comments, I am encountering difficulties. Upon selecting the radio button, ther ...

Tips for embedding an image or icon within a button using jQuery

When generating buttons on the fly, I rely on the following code: var dynButton = $('<input/>').attr({ type: 'button', id:'idDynBtn', class:'clsDynBtn', name:'DynBtn', value:'Tool' }); Is i ...

What is the most efficient way to align a localStorage variable with its corresponding page?

In my current project, I have developed a component that is utilized in an online science lab setting. To ensure continuity for researchers who navigate away from the page and return later, I have integrated the use of localStorage. The goal is to preserv ...

Making JSON function in Internet Explorer

I'm encountering an issue retrieving data from a JSON feed specifically in Internet Explorer. Here's the problem. It functions correctly in Firefox, Chrome, and Safari, but fails to alert in IE: function perform_action(data){ alert(data); } ...

Having Trouble With Your Font Display?

I am confident that my code is correct. Here's a snippet from what I've done: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="homepage.css"/> </head> <body> <div id="menu"> &l ...

The functionality of JQuery ceases to function properly once the BxSlider plugin is activated

I've encountered a strange issue while using the BxSlider plugin of jQuery on my page. When I implement the code for the slider with BxSlider, all other custom functions seem to stop working without any errors being displayed in the console. I've ...