3

I'm trying to use JQuery to add/remove classes as part of a function that uses links to switch around the main content divs on my site.

Here is my JavaScript:

$(document).ready(function () {
  var clickHandler = function (link) {
     $('.tab').hide();
     $('#options_' + link.data.id).show();
     $('.selected').removeClass('selected');
     $(this).addClass('selected');
   }

   $('.link1').bind('click', {id:'1'}, clickHandler);
   $('.link2').bind('click', {id:'2'}, clickHandler);
   $('.link3').bind('click', {id:'3'}, clickHandler);
});

Here is the HTML of the divs I'm switching (this part works):

<div id="options_1" class="tab">
<h3>Your Feed</h3>
<?= $userFeed ?></div>

<div id="options_2" class="tab">
<h3>All Recent Activity</h3>
<?= $feed ?>

</div>
<div id="options_3" class="tab">
<h3>Trends</h3>
Coming Soon!
</div>

And here is the HTML of the links in the sidebar portion of the page that control the div switching. The class "selected" should be removed from option 1 and added to whatever other link the user selects, but this isn't happening. The class isn't being changed at all.

<ul id="feedOptions">
<li><a href="#" id="1" class="link1" class="selected">Your Feed</a></li>
<li><a href="#" id="2" class="link2">All Activity</a></li>
<li><a href="#" id="3" class="link3">Trends</a></li>
</ul>

Like I said above, I can't get the 'selected' class to change at all. Any suggestions?

2 Answers 2

4

You have multiple class attributes on a single element, instead of this:

<a href="#" id="1" class="link1" class="selected">Your Feed</a>

You should have this (single attribute, separate classes with a space):

<a href="#" id="1" class="link1 selected">Your Feed</a>
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, of course! Thanks so much, though I feel a bit like an idiot. You wouldn't believe how long I stared at that and forgot that I had added an extra 'class.' Works like a charm.
1
$('.link1,.link2,.link3').bind('click', function() { $(this).toggleClass('selected'); });

2 Comments

This doesn't toggle the class on other elements (removing the previous selected) :)
@Nick: yep. that was not a complete answer to his question but the tip how he could make his code shorter ;-)

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.