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

Choose specific nodes using the XPath query language

I need help with an HTML snippet: <td> <span class="x-cell">something</span> <span class="y-cell">something</span> <span class="z-cell">something</span> A text <span ...

The occurrence of the "contextmenu" event can cause disruption to the execution of a function triggered by the "onmousemove" event

Currently in the process of developing a Vue application utilizing a Pinia store system. Within my BoxView.vue component, I have created a grid layout with draggable elements that have flip functionality implemented within the BoxItem.vue component. Spec ...

Error Alert: jQuery AJAX Event is not defined in Firefox Browser

This snippet works perfectly on Webkit browsers, but for some reason, it's not functioning in Firefox. I have a feeling that I need to include "event" within parentheses somewhere, but I'm unsure about the correct placement. Any ideas? html < ...

Leverage the power of option values to make dynamic text edits with jQuery

I've been struggling to update the text in an option without success, here's my code: View <select id="plano"> <option selected>Choose plan...</option> @foreach($foodplans ...

Problem with keyframe animations in Internet Explorer 10

My CSS animation works flawlessly in all modern browsers, except for IE10 which is causing some trouble. It appears that IE is having difficulty properly rotating 360deg. I am still searching for a workaround that won't compromise the functionality in ...

Shortcode for AJAX to display the total amount in Woocommerce cart

I've created a custom snippet to show the total cart amount using a shortcode. This snippet is utilized on the checkout page of my website, which features a multi-step checkout process. The display is made before order validation takes place. add_shor ...

Executing numerous HTTP requests in a single Node.js HTTP request

I am attempting to make a single URL call that will fetch multiple URLs and store their JSON responses in an array, which will then be sent as the response to the end user. Here is what my code looks like: var express = require('express'); var ...

Incorporate different courses tailored to the specific job role

https://i.stack.imgur.com/iGwxB.jpg I am interested in dynamically applying different classes to elements based on their position within a list. To elaborate: I have a list containing six elements, and the third element in this list is assigned the class ...

Toggle class for section collapse/expand using jQuery

My code to expand/collapse Q&A sections is not quite working as expected. I am attempting to add a class to the "A" element to show if it's collapsed or expanded, but it seems like I might be making it more complicated than it needs to be... $(".A"). ...

Ways to verify the efficiency of view engines such as Pug, EJS, and HTML

Currently, I am in the process of creating a Node.js Web Server. Initially, I decided to use pug as my view engine for this project. However, the Web Designer provided me with HTML files that have a very different syntax from pug. As a result, I am cons ...

Outputting an object using console.log in Node.js

When I print the error object in nodejs, the result of console.log(err) appears as follows: { [error: column "pkvalue" does not exist] name: 'error', length: 96, severity: 'ERROR'} I'm curious about the information enclosed ...

Using JavaScript, implement the array.filter method on a JSON array to retrieve the entire array if a specific property matches a given

Help needed with filtering an array: In the user_array, there are arrays that need to be compared to see if the header_info.sap_number matches any value in the valid_sap_number array. If a property value matches anything in the valid_sap_number array, th ...

Add the "multiple" attribute to ui-select only if certain conditions are met

I am attempting to dynamically add the multiple attribute to a ui-select directive based on the value of a specific property by using the ng-attr- directive. Unfortunately, this method is not functioning as expected in my case. To better illustrate the iss ...

Creating a nested tree structure array from a flat array in Node.js

I have an array structure that I need to convert into a tree array using node.js. The current array looks like this: var data= [ { "id1": 1001, "id2": 1002, "id3": 1004, ... } ...

Calculating totals in real-time with JavaScript for a dynamic PHP and HTML form that includes quantity,

I have created a dynamic form with fields and a table that adjusts based on the number of results. Each column in the form represents name, quantity, price, and total price. The PHP and SQL code runs in a loop to populate the list depending on the number ...

Center alignment is not being applied to the SVG element

I am currently working with React and when my component renders, it displays an SVG inside a div. Here is a snippet of the code: render() { return( <div class="myClass"> <svg> ... </svg> </div> ); ...

Struggling to retrieve a JSON object from an Express and Node application, only receiving an empty result

Can anyone assist me? I'm having trouble with the res.json() function in my code. It seems to work after the first request, but not after the second. Right now, my application is quite simple - it scrapes user data from social media platforms like Twi ...

The function get_template_directory_uri() returned an unexpected string error

Exploring WP themes has been an interesting journey for me. Currently, I am working on creating a shortcode for some html/script and encountering an issue with enqueuing the js file. My initial query is about whether I am loading this from the correct loc ...

Select a random option from the dropdown menu

I have the following script: <script> function $(id) { return document.getElementById(id); } function getImage() { $('loader').src='/misc/images/loading.gif'; var url = "http://mouse ...

Having trouble getting the Click Element with CSS selector to function properly in Google Tag Manager?

How can I detect a click on the specified element by using the "Click Element" variable in Google Tag Manager? <a href="https://amazon.in/product-id" target="_blank" class="amazon-btn"> <div> <span&g ...