2

I have a navigation menu with about 10 items, and I put together this code to update the links for which is selected and which is not. It manually updates classes. The problem is, as you can probably tell, its inefficient and its a pain to update. Is there a better way of doing it?

$('#Button1').click(function(){
        $('#Button1').addClass("selectedItem");
        $('#Button2').removeClass("selectedItem");
        $('#Button3').removeClass("selectedItem");
        $('#Button4').removeClass("selectedItem");
        $('#Button5').removeClass("selectedItem");
        $('#Button6').removeClass("selectedItem");
        $('#Button7').removeClass("selectedItem");
        $('#Button8').removeClass("selectedItem");
        $('#Button9').removeClass("selectedItem");
        $('#Button10').removeClass("selectedItem");
    });

3 Answers 3

2

You could try something like this -

$("[id^='Button']").removeClass("selectedItem");
$('#Button1').addClass("selectedItem");

This will first remove all the selectedItem classes from any element which has an id attribute starting with "button". The second command then adds the class to Button1

You could also simply bind all the elements with the same handler like this -

var $buttons = $("[id^='Button']");

$buttons.on('click', function ()
{
  $buttons.removeClass("selectedItem");
  $(this).addClass("selectedItem");
});

For each element, when clicked, the class will be removed - the element that was clicked with then have the class added.

Checkout the Attribute Starts With Selector [name^="value"] selector.

Sign up to request clarification or add additional context in comments.

1 Comment

@sco - Thanks for that! Caching these broader selectors is always a good idea.
2

I would suggest using classes because this is exactly what they are for - to denote groups of elements. While you can easily select your buttons using the method proposed by Lix (and you should use this method if you can't modify HTML), using class is a more unobtrusive:

var $buttons = $('.button').on('click', function() {
    $buttons.removeClass('selectedItem');
    $(this).addClass('selectedItem');
});

Meta example: http://jsfiddle.net/88JR2/

Comments

0

You could have a class .button and apply it to all your buttons then

$('#Button1').click(function(){
    $('.button').removeClass("selectedItem");
    $('#Button1').addClass("selectedItem");

});

1 Comment

Adding a class to all of the related elements is a great idea. But your implementation would still need a separate handler for each button. The problem in this question is about not repeating yourself, so your solution doesn't really solve it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.