M_B216
M_B216

Reputation: 103

How to change html element ( li ) class in Asp.Net?

I have a list ul (its id is menu_) with multiple elements li, these lis are initially in class in-active, I want when the client click on one li to be redirected to another page and then change the CssClass of this li to active.
I've tried this JS code but didn't work, it didn't redirected to the another page after client click an li (it remains in the same page):

$(function () {
    $('#menu_ li').click(function () {
        $("li.active").removeClass("active");
        $(this).addClass("active");
        return false;
    });
});

Upvotes: 0

Views: 210

Answers (2)

HaukurHaf
HaukurHaf

Reputation: 13816

You are mixing server-side/client-side functionality here. Your JS code is purely client-side and it will toggle the classes correctly, but having return false; means that the link will not be followed, so no redirection will be performed (no server side code will be run).

You could remove return false; and then the classes will be changed and the redirection will be performed, but once the redirect has been done, you have a new page and the class changes will not persist.

You basically have three options:

  1. Have a JS code as Imadoddin Ibn Alauddin suggest above inside each child page which takes care of setting the correct element in the navigation to active once the page loads.

  2. Somehow persist the state between requests, once you add the active class, save the state in a cookie or local storage for example. Then every time a page loads, check if the cookie/local storage contains such data and update the state accordingly.

  3. Change the state of the navigation on the server side, so once each page loads, add the active class to the corresponding page.

I'd recommend option 3.

Bottom line: You cannot mix things like you are doing now. Having return false; will cancel the redirection out. Once the redirection is performed, a new page will load and the navigation will be reset so any change you made using JS before the redirection was done is gone.

Upvotes: 0

Imad
Imad

Reputation: 7490

You can do this inside each page.

$("li.active").removeClass("active");
$( "ul#menu li:nth-child(n)" ).addClass("active");

Keep this code in ready event.

n is number of li that you want to add class to.

Upvotes: 2

Related Questions