"Enhance your website with dynamic link styling by using jQuery to add

Hi there, I'm currently working on an off canvas menu and I'm trying to figure out how to add a class that will highlight the active menu item. However, the jquery code I have doesn't seem to be doing the trick. I've scoured the web for solutions but nothing seems to work. Any suggestions or ideas would be greatly appreciated!

<nav class="site-menu">
       <div class="menu-list"> 
        <ul>
            <li><a href="portfolio.php">portfolio</a></li>
            <li><a href="projects.php">projects</a></li>
            <li><a href="process.php">process</a></li>
            <li><a href="blog.php">blog</a></li>
            <li><a href="contact.php">contact</a></li>
        </ul>
        </div>
    </nav>

css

 .site-menu ul {
    list-style: none;
    padding: 20px;
    margin: 0;
}

.site-menu ul li a {
    display: block;
    width: 100%;
    height: 50px;
    line-height: 50px;
    color: #7f7f7f;
    background: transparent;
    text-decoration:none;
}

.menu-list{
    position: absolute;
    top: 80px;
    margin-left: 10px;
    font-family: 'Open Sans', sans-serif;
    font-weight: 400;
    text-transform: uppercase;
    letter-spacing: 2px; 
    text-align: left;
     }

.active {
    color:#fff;
}

script

var selector = ".site-menu li";

$(selector).click(function(){
    $(selector).removeClass('active');
    $(this).addClass('active');
});

Answer №1

In order to achieve the desired styling, it is important to enhance the specificity of your CSS selector:

.site-menu ul li.active a {
    color: #fff;
}

Otherwise, the rule .site-menu ul li a will take precedence over this one.

To learn more about CSS specificity, check out this resource: CSS Specificity: Things You Should Know.

See a demonstration here: http://jsfiddle.net/6ck1Lg0w/

Answer №2

Give this a shot:

const menuSelector = ".site-menu li";

menuSelector.on('click', function(){
    menuSelector.removeClass('active');
    $(this).addClass('active');
});

Answer №3

To make the selection, update your current selector with the code provided below:

const selector = ".navigation-menu ul li a";

Answer №4

Upon loading a new page, any javascript changes will be reset. However, you can determine which page is currently active by running the following code when the page loads:

Javascript:

(function($){
    $('.site-menu li a').each(function(){
        if( $(this).attr('href') == window.location.pathname ) $(this).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

Safari displaying elements without following font styling specified in CSS

I have a select element in my web page, and I've customized the font using CSS: @font-face { font-family: myFont; src: url('myFont.woff'); } body select{ font-family: myFont; } After testing in Chro ...

Issues arise when trying to use a JavaScript function within an HTML form, with an error message stating "TypeError: total

Recently, I encountered an issue with a straightforward JavaScript function that calculates user input. The function performed as expected when I tested it without the form tag. However, when I tried using the same code within the form tag, an error was di ...

Achieving flexbox's equal height for Bootstrap's Navbar and content

I am faced with the challenge of designing a layout where a content grid occupies the entire remaining page, while also incorporating a navigation bar. To achieve this, my approach involves placing the navigation bar within a flex container and the conten ...

Unraveling HTML elements within a string using MongoDB: A step-by-step guide

Currently, I am in the process of creating a blog from scratch as a way to enhance my skills. The posts' content is stored as a long string in MongoDB with some random HTML tags added for testing purposes. I am curious about the conventional method fo ...

Struggling to create a photo grid design that meets my expectations

I'm struggling to recreate this particular photo grid. Any tips on how I can achieve it? Check out the image here Just to clarify, I had a working prototype see image description using flexbox. However, one image didn't fit well so I resorted to ...

What is the method for implementing circular looping in the "auto scroll" feature of the latest jCarousel version (3.0)?

Is there a way to configure the 'circular' wrap setting and continuous looping in the latest version of jCarousel (3.0) auto scroll plugin? I am seeking a method for the items to continuously loop without pausing, similar to how it functioned in ...

Is it possible to achieve wordpress + nginx + https for just a single page?

I am facing a challenge with my WordPress site, which is hosted on Nginx running on Windows Server 2012 R2. I want to enable HTTPS on specific pages like /cart/, /my-account/, and /checkout/, but all the resources are still being loaded over HTTP, resultin ...

jQuery Decimal Calculations

Could anyone help with how to format decimal numbers in these calculations and also include the interest code: function reCalc(borrowValue) { $("#targetVal").html("&pound;" + borrowValue); var borrowBC = Math.floor(borrowValue * 1.25); var ...

Add array as an element within another array

After initializing the data, I have an object structured like this and I am able to push data using the method below: myObj = { 1: ["a", "b", "c"], 2: ["c", "d", "e"], } data: { types: {} }, methods: { pushValue(key, value) { var ...

Design a circular text element using Tailwind CSS

Just starting out as a web developer and running into some issues with Tailwind CSS. Here's what I'm trying to achieve: https://ibb.co/KL8cDR2 This is the code I have right now: <div class="w-1/2 h-10 rounded-full bg-gray-400" style ...

Permanently erasing input values in an HTML textbox with the power of jQuery

I am working with a form field for the user name: <%: Html.TextBoxFor(model=>model.UserName)%>. I need to check if the user name is available or not. If it's unavailable, then I want to clear the TextBox. I tried using the query $("#UserName" ...

Prevent Index.html from being stored in cache

Currently, Index.html contains numerous JavaScript files that are concatenated and minified into a single file. This consolidated file undergoes a name change due to the filerev grunt task. Although this process functions correctly, an issue arises when I ...

The function stringByEvaluatingJavaScriptFromString is failing to execute

I have tackled similar problems that have been posted in this forum, however my issue remains unresolved. I am attempting to utilize stringByEvaluatingJavaScriptFromString in swift, but it is not functioning as expected. Any assistance would be greatly app ...

I am struggling to remove the div from its normal flow as it stubbornly remains positioned below

Is there a way to add a "contact" card to my website's right-top corner in a sticky position? I currently have a div block in that area which is blocking the contact card. Can anyone suggest a solution for this? https://i.stack.imgur.com/umC7B.jpg &l ...

What are some strategies for maintaining a responsive layout with or without a sidebar?

I've made the decision to incorporate a sidebar on the left side of all pages across my website. This sidebar must have the ability to be either hidden or shown, without overlapping the existing content on the page. However, I'm encountering an ...

The expected result is not being returned when clicking a jQuery button

Below is the jQuery code snippet that I am using: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <script> $(document).ready(function() { ...

Attach an @click event to the href attributes within an array

I am currently working on code to populate a datatable with rows. Each row in the datatable contains an update link, which when clicked should trigger the ShowModal() method. How can I invoke the ShowModal() function using this <a> element? < ...

Failure in rendering components with React and ElectronThe issue of rendering components with

As a newbie to the world of React and Electron, I have been experimenting with separating my components into different JSX files and importing them to render in div tags within my index page for an Electron app. However, I'm facing some confusion as i ...

Is there a way to append more selected elements to an existing array in PHP?

I'm encountering issues with a list box that is set to multiple selection. My setup consists of 3 individual list boxes: Categories (single select), Jobs (single select), and Tasks (multiple select). When a user selects an item in Categories, an ajax ...

What is the best way to regain grid focus following a data reload in ExtJS?

Within my ExtJS view, there is a grid where users can select an entry along with a panel displaying details about the selected row. However, every time a different row is chosen, the view is reloaded causing the grid to lose focus for keyboard navigation. ...