Andrew
Andrew

Reputation: 3589

Setting id using jQuery

I've been trying to create a menu where after the user clicks on a menu item, that item will be set to active and the previous active item will be deselected. However, I'm not too sure what I'm doing wrong: http://jsfiddle.net/Z5M2a/15/

Edit: switched around id and class, though still not sure what's wrong Javascript:

$(document).ready(function(){
    $('#menuOption').mousedown(function() {
          $('#menuOption').attr('class', '');
          $(this).attr('class', 'active');

    });
 });

HTML:

<div id="side-bar"> 
                <ul class="side-nav">
                  <li class="divider"></li>
                  <li id="menuOption" class="active"><a href="#">Link 1</a></li>
                  <li class="divider"></li>
                  <li id="menuOption"><a href="#">Link 2</a></li>
                  <li class="divider"></li>
                  <li id="menuOption"><a href="#">Link 3</a></li>
                  <li class="divider"></li>
                  <li id="menuOption"><a href="#">Link 4</a></li>
                  <li class="divider"></li>
                </ul>   
           </div>

Any help would be appreciated, thanks!

Upvotes: 1

Views: 102

Answers (5)

ArnauOrriols
ArnauOrriols

Reputation: 584

$('mouseOption') doesn't exists!

$(".menuOption")

which means "select those elements of class menuOption" (point means "class")

Upvotes: 0

Evgeny
Evgeny

Reputation: 6290

Change $('mouseOption') to $('.menuOption')

Other then that you should be never using list element as divider (use CSS instead)

Upvotes: 1

feitla
feitla

Reputation: 1334

You are not referencing the element correctly and you should really be adding classes not change the id

FIDDLE

you can also use the click call instead of mousedown

$(document).ready(function(){
    $('.menuOption').click(function() {
        $('.menuOption').removeClass('active');
        $(this).addClass('active');
    });
});

Upvotes: 1

federicot
federicot

Reputation: 12341

It's better to use an extra class for this, as the purpose of ids is to give the element a unique identity, not a "state".

$(document).ready(function () {
    $('.mouseOption').mousedown(function () {
        $('.mouseOption').removeClass('active');
        $(this).addClass('active');
    });
});

Upvotes: 0

Jason P
Jason P

Reputation: 27012

Element ids should generally be static. Try changing the class instead.

Also, change mouseOption to .menuOption. Here's a working fiddle:

http://jsfiddle.net/ByXJc/

$(document).ready(function(){
    $('.menuOption').mousedown(function() {
        $('.menuOption').removeClass('active');
        $(this).addClass('active');
    });
});

Upvotes: 4

Related Questions