Updating the style sheet of a selected menu item on an ASP.NET master page

I created an asp.net master page with a menu setup like this:

 <menu id="menu">
    <nav id="main_nav">   
     <ul id="menu-primary">
      <li ><a href="./">Home</a></li>
      <li><a href="staff.aspx">Staff</a></li>
      <li><a href="">Sales</a></li>
      <li><a href="">Support</a></li>
      <li><a href="">Administration</a></li>
     </ul>
    </nav>
   </menu>

In the master page, I wanted to change the CSS for the menu item when it is clicked. I implemented this jQuery script:

<script type="text/javascript">
    jQuery(document).ready(function () {
        $('ul li a').each(function () {
            var text_splited = $(this).text().split(" ");
            $(this).html("<span>" + text_splited.shift() + " " + text_splited.join(" ") + "</span> ");
        });

        // click on the first item on page load
        $('#menu-primary li').eq(0).click();

        $('#menu-primary li').click(function (e) {
            alert('here');
            // remove all active classes
            $('#menu-primary li').removeClass('current-menu-item');
            // add active class to clicked item
            $(this).addClass('current-menu-item');
        });
    });


</script>  

Here is the corresponding CSS:

nav#main_nav ul li.current-menu-item a,
nav#main_nav ul li a:hover {background: url("../images/menu_bg.png") no-repeat scroll 0 -149px transparent; border-bottom:1px solid #edf7ff}
nav#main_nav ul li.current-menu-item a span,
nav#main_nav ul li a:hover span{background: url("../images/menu_bg.png") no-repeat scroll 100% -118px transparent;}

The code to automatically click on the first item on page load works fine:

// click on the first item on page load $('#menu-primary li').eq(0).click();

     $('#menu-primary li').click(function (e) {
         // remove all active classes
         alert($('#menu-primary li').html());
         $('#menu-primary li').removeClass('current-menu-item');
         // add active class to clicked item
         $(this).addClass('current-menu-item');
         return false;
     });

However, the page doesn't load because the function returns false.

The alert message does appear, but the CSS is not being applied to the clicked item.

Answer №1

Could you attempt something similar to the following

$("#menu-primary li.current-menu-item").removeClass("current-menu-item");
$(this).addClass("current-menu-item");

To designate the first menu item as selected by default, add the current-menu-item class to it like so

<li class="current-menu-item"><a href="#">Menu Item</a></li>

View Example in Action

Different method based on Page URL

$('#menu-primary li a').each(function() {
    var path = window.location.href;
    var current = path.substring(path.lastIndexOf('/'));
    var url = $(this).attr('href');
    if(current=="")
    $('#menu-primary li a').first().addClass('current-menu-item');


        if (url == current) {

            $(this).addClass('current-menu-item');
    };
});     

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

How can I modify the text that appears when hovering over an element?

Can the displayed text be altered on mouse hover? For instance, can I change the text of a H1 tag when hovering over it using HTML, CSS, and JavaScript? ...

Unable to interact with elements upon completion of ajax load()

Having trouble executing functions on Ajax-loaded content in a div element. Any suggestions on how to make it work? var key = null; var keyProperties = null; function OnNodeClick(s, e) { key = e.node.name; //alert('key= '+ key); $("# ...

Press the second form submit button after the completion of another Observable

Below is the unique process we aim to accomplish using solely RXJS Observables: Press Login button (form with username & password). We bind Observable.fromEvent with our form. Upon submitting the form, call loginUser() to send an http request to serv ...

Issues with executing basic unit test in Angular Js

THE ISSUE: In an attempt to create unit tests for my Angular application, I set up a basic test app and wrote a simple unit test. However, the test is not functioning as expected. APPLICATION CODE: var app = angular.module( 'myApp', [] ); app ...

What is the best method for storing a client-side token in nextjs 13 with the App Router update?

We are currently using a nextjs 13.5 web application. The new app router paradigm in Next.js 13 involves all components, including client components, going through their initial render on the server during a full page load (such as after a refresh). Accord ...

Using React, a link to the same component is created, but a subcomponent is mistakenly using an outdated version of

Here, we have a SubComponent and a MainComponent created to showcase an image collection. The Subcomponent allows you to toggle between pictures in the collection using the onclick() event. The MainComponent also includes links to other collections, which ...

Enter the UL element and modify the LI class if it contains the .has_children class

Seeking assistance in navigating through a UL element to modify the LI and nested UL classes when .has_children is detected. Take a look at this example: <ul class="nav navbar-nav"> <li class="first current parent">Link1</li> < ...

Transforming a Nestjs string object into JSON data

I need to convert this to JSON format. I attempted to use JSON.parse(), but encountered an error. "{"status":"00","message":"OK","access_token":"2347682423567","customer":{"name":"John Doe","address":"Mr. John Doe 34 Tokai, leaflet. 7999.","util":"Demo Ut ...

Improper CSS styling leading to incorrect image size

I've got this awesome parallax image on my website (the majestic nature one) Here's how the page looks normally But sadly, it's not properly sized. When I check in Chrome dev tools, it appears like the image below, which is how I want it to ...

Differences between Request.QueryString[], Request.Query.Get(), and HttpUtility.ParseQueryString() functions

After searching SO, I couldn't find a comparison between all three methods of parsing query strings. If anyone knows of one, please share. There are various ways to parse query strings in a request, but the best method should handle missing values an ...

A scheduled task in Node.js set to run every day at 2 AM

My nodejs cron currently runs every 5 hours using the code below: cron.schedule("0 0 */5 * * *") How can I modify it to run daily at 2 AM instead? Thank you ...

What could be the reason for data.map not being recognized as a function?

I developed the following React component: import React, { useState } from 'react'; export default function Example(){ var friend = function (id, firstName, lastName){ this.id = id; this.firstName = firstName; this.lastName = lastN ...

AngularJS: default option not being selected in dropdown menus

I need assistance with a dropdown list issue. See the code snippet below: My Controller (function(angular) { 'use strict'; angular.module('ngrepeatSelect', []) .controller('ExampleController', ['$scope', functi ...

Issue with Vue-Validator form validation not functioning properly on JS Fiddle

I'm having trouble with vue-validator on JSFiddle. Can someone please assist in troubleshooting the issue so I can proceed with my main question? Check out JSFiddle Html: <div id="app"> <validator name="instanceForm"> & ...

How can you utilize CSS grid to position an alternate symbol alongside ordinary text?

Does anyone have suggestions on how to align an "alt symbol" with "regular text"? I'm struggling to center both elements without resorting to hacky solutions. Currently, I am using CSS grid, but I am open to exploring other solutions that are easy an ...

The knockout click event isn't functioning properly for a table generated by ko.computed

My goal is to connect a table to a drop-down menu. Here are the key points of what I'm trying to achieve: The drop-down should list MENUs. Each MENU can have multiple MODULES associated with it, which will be displayed in the table based on the ...

Pattern without anything to duplicate

Could someone help me figure out what I'm doing wrong with this regular expression? I need to create a regex that matches phone numbers in three specific formats: "+38 (093) 937-99-92", "093 937 99 92", and "(093) 937 99 92". As I started working on ...

Issue with uploading files

Hey there! I encountered an issue with a file upload in a user control within an UpdatePanel on my ASPX page. Even after dynamically adding the trigger, the FileUpload.hasFile property always returned false. Any thoughts or suggestions? In case someone e ...

JavaScript sticky navigation bar - error displayed in console

Hey there, I'm having an issue with my Sticky-menu. I've been trying to troubleshoot it but keep getting these console error messages: 1. Cannot read property 'offsetTop' of null at HTMLDocument. 2. Cannot read property 'class ...

When the remove button is pressed, I want the checkbox to become unchecked

I need help with unchecking a checkbox after confirming the removal of items. Can someone provide guidance on how to achieve this? Below is the code I am using: JavaScript: $(".rem-btn").click(function(){ var remConf = confirm("Are you sure you ...