Emphasize the active page in the main menu

I'm struggling to use JavaScript and jQuery to highlight the current list item on my main menu. As a beginner in scripting, I am having trouble figuring out what's wrong with the code. Here is the code snippet that I have been working with.

<ul id="#mainMenu">
    <li><a href="/home">Home</a></li>
    <li><a href="/about">About</a></li>
    <li><a href="/contact">Contact</a></li>
</ul>

<script type="text/javascript">
$('#mainMenu li a').on('click', function(){
    $('li a.active').removeClass('active');
    $(this).addClass('active');
});
</script>

Answer №1

For those who prefer adding classes to the menu based on the current URL rather than using the .click function, I have a solution.

$(document).ready(function(){
    $("a[href*='" + location.pathname + "']").addClass("active");
});

Upon page load, this script checks all anchor tags against the current URL and applies the .active class to any matching elements.

Answer №2

I have a valuable addition to Jay's approved answer. In some cases, your URL might differ, such as 'posts' for one menu item and 'posts/create' for another. The code provided in the accepted answer will highlight both of these URLs. To prevent this, you can make the following adjustment: utilize window.location.href instead of location.pathname and remove the asterisk (*) after href:

$(document).ready(function(){
    $("a[href='" + window.location.href + "']").addClass("active");
});

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

``The ngRoute module is causing issues with loading in my application

Just delved into the world of AngularJS and encountered a challenging 'Routing' assignment for some hands-on practice. To my disappointment, I encountered a couple of errors when running the application: Error 1: Error: $injector:modulerr Mo ...

Array of Ascending Progress Indicators

I currently have a progress bar that I'm happy with, but I want to enhance it by incorporating stacked progress bars. My aim is to have the progress bar behave in the following way when an option is selected: https://i.stack.imgur.com/Pw9AH.png & ...

Guide to incorporating tesseract OCR into a Cordova/Phonegap application

My attempts to use Tesseract OCR with my app have been unsuccessful despite following the instructions provided here. After inspecting the code using Google Chrome Dev console through the WebView, I encountered an error: Uncaught SyntaxError: Unexpected ...

How can we use the nth-of-type selector to target a set of eight elements in a

I am trying to style a group of divs in such a way that every set of eight elements will have the same left positioning. Rather than just styling every eighth element individually, I want to apply the styling to groups of eight elements at once. However, ...

Eliminate the dimming background on a discussion thread in Discourse

Working on customizing a theme for my blog using the Discourse engine has been quite interesting. I have noticed that every post, or "topic," loads with a blue background that quickly transitions to the main background color. You can take a look at an exam ...

Transform Data into Serialized Format for HTTP Transmission

Is it possible to convert the following Record into a serialized Form Data string (Content-Type: application/x-www-form-urlencoded) as shown below? TError = record code: Word; message: String; end; TState = record caption: String; address: Cardin ...

What are the steps for generating website endpoints using search query outcomes?

I am currently working on a ReactJS website as a part of my web development bootcamp project. One interesting feature I have incorporated is a search functionality that uses Flask routes to connect ReactJS endpoints (../Language.js) with my Sqlite3 databa ...

Is a component updating an unregulated text input to be controlled?

Whenever I attempt to input information into the form and save it in the state, I encounter the following issue: Warning: A component is converting an uncontrolled text input to a controlled one. Input elements should not transition between being contro ...

Transferring information between Flask and JS using AJAX for a Chrome extension

I'm experimenting with AJAX calls to establish communication between my Javascript frontend in a chrome extension and the Flask API where I intend to utilize my Machine Learning algorithms. content.js console.log("Let's get this application ...

In Javascript, a variable is being defined by combining a string with another variable through concatenation

Hey, I'm relatively new to working with Javascript and am facing an issue that I believe can be resolved easily with the right syntax. The problem lies in setting a variable (totalRow1) where it needs to be concatenated with a string and another vari ...

There is no element available to input text using send_keys in Selenium

Currently learning about selenium, please pardon any errors. Thank you :) I am trying to scrape a website that allows users to create blogs on 'tistory' using selenium. In order to publish an article, I need to choose between default mode, mark ...

Troubleshooting the malfunction of Jquery's timepicker plugin developed by John Thornton

I'm having trouble getting my time picker to function properly (i.e., nothing happens when I click on the input field). I am using the example provided at: Here is the code snippet I am trying to implement: html: <!-- Time picker --> <scrip ...

Slide feature in Drupal Views allows you to create dynamic

This is the design I currently have: https://i.stack.imgur.com/P6spc.jpg For example, when you click on the "Structure" header, it opens up the contents and shows an image. I have created a content type and installed Views. I have separated the image, h ...

Is there a way to create a transparent color for the Dropdown Toggle?

As I work on expanding my understanding of HTML and Bootstrap, utilizing Bootstrap version 5.3.0 Alpha 3, I encounter an issue with the Dropdown feature. Typically, when a Dropdown is used within an element such as an icon or text, it displays an arrow sym ...

"Although getJSON is successfully returning values, the issue lies in these values not being added to

I am facing an issue with my getJSON request where it is returning the correct values but not adding them to the list Below is the code snippet: <script type="text/javascript> $(document).ready(function() { $("select#make").change(function(){ $(&a ...

Filter error - Unable to retrieve property 'toLowerCase' from null value

When filtering the input against the cached query result, I convert both the user input value and database values to lowercase for comparison. result = this.cachedResults.filter(f => f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1); This ...

Transform HTML into a PDF document using ABCpdf

Currently, I am working on developing a web application that involves the use of ABCpdf to convert HTML pages into PDF files. The HTML pages in question contain dynamic elements implemented using JavaScript. In an attempt to address this issue, I have exp ...

Issue with the height of nested divs within ion-col not being rendered properly on iOS devices

I am currently using Ionic 2 for my project. Presented below is the template I have: HTML Code <ion-grid> <ion-row> <ion-col width-20> <div> <img src="http://www.kacholy.com/new_site/pic/image_727 ...

Gulp halts when watching code and reloads upon any changes made

Hey there, I'm new to GULP and could use some help... I've been trying to configure GULP for a template that uses AngularJS. When I run the gulp command, the console displays the message "**Done Waching code and reloading on changes" but nothing ...

Designing an adaptive div for textual content without relying on Bootstrap

I am working on creating a responsive div that includes an image, text, and spacing between the divs. Initially, I had divs with spacing and text but they did not resize properly when more text was added. I am aiming to achieve a layout similar to this: ht ...