HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Applying an id attribute based on a variable's value

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
valuebasedattributeapplyingvariable

Problem

I have the following code that checks the value of a variable and then applies the correct id attribute accordingly. The value of menuLink will have the same value of one of the parts of .mainmenu a href path name.

Is there a way to simplify this so it can search the href path of .mainmenu a instead of explicitly stating each one?

if (menuLink == "whatsnew") {
    $('.mainmenu a:eq(1)').attr('id', 'active').addClass("disable");
} else if (menuLink == "products") {
    $('.mainmenu a:eq(2)').attr('id', 'active').addClass("disable");
} else if (menuLink == "contact") {
    $('.mainmenu a:eq(3)').attr('id', 'active').addClass("disable");
} etc.....

Solution

Don't change IDs. IDs are supposed to identify a specific element, regardless of any state. "Active" should be a class.

The .mainmenu class should probably also be an ID. It's the "main menu" - that's its identity. Classes are for when you have multiple elements that are "of the same class", i.e. they share some functionality or styling. (If you have multiple things called "main menu", you have other problems.)

Using an active class will also let you use the IDs to find the link you want make active.

$("#mainmenu a.active").removeClass("active")
$("#" + menulink).addClass("active");


Basically: Find the currently active link, and remove the "active" class from it. Then find the link with the ID you're looking for, and set that to active by adding the class.

Code Snippets

$("#mainmenu a.active").removeClass("active")
$("#" + menulink).addClass("active");

Context

StackExchange Code Review Q#77647, answer score: 4

Revisions (0)

No revisions yet.