I have a menu that links to content on the same page and through jQuery fades div’s in and out, working perfectly.
The first link in the navigation has a class attached to it (current_page_item) and I would like, on click of any other link in the navigation, to remove that class and add it to the clicked link.
So far I’ve tried something like:
$(function() {
$("#nav-links a").click(function(){
$("#nav-links ul li").removeClass("current_page_item").find("li:last a").addClass("current_page_item");
});
});
which doesn’t work.
I’m very new to javascript so any help would be appreciated.
Thanks!
EDIT:
Here is the HTML for the navigation:
<div id="nav-wrap">
<ul class="group" id="nav-links">
<li class="current_page_item"><a href="#recent" class="linkclass recent">RECENT</a></li>
<li><a href="#work" class="linkclass work">WORK</a></li>
<li><a href="#who" class="linkclass who">WHO</a></li>
<li><a href="#services" class="linkclass services">SERVICES</a></li>
<li><a href="#contact" class="linkclass contact">CONTACT</a></li>
</ul>
</div>
EDIT 2:
Using the answers below it still doesn’t seem to achieve what I want. Perhaps it’s because of the jQuery plugin I’m using (magic line). Link
So basically I’d like the ‘line’ to stay underneath what is clicked. Which works if I load a new page with the ‘current_page_item’ in the right place, but as I’m fading DIVs in and out, I can’t do that.
The line bounces back to the li item with ‘current_page_item’ class. Perhaps this code can be modified to add the class to the clicked element?
Here’s the code.
$(function() {
var $el, leftPos, newWidth,
$mainNav = $("#nav-links");
$mainNav.append("<li id='magic-line'></li>");
var $magicLine = $("#magic-line");
$magicLine
.width($(".current_page_item").width())
.css("left", $(".current_page_item a").position().left)
.data("origLeft", $magicLine.position().left)
.data("origWidth", $magicLine.width());
$("#nav-links li a").hover(function() {
$el = $(this);
leftPos = $el.position().left;
newWidth = $el.parent().width();
$magicLine.stop().animate({
left: leftPos,
width: newWidth
});
}, function() {
$magicLine.stop().animate({
left: $magicLine.data("origLeft"),
width: $magicLine.data("origWidth")
});
});
});
You can reach clicked element with
$(this)and access to it’s parentlielement withparent()to addcurrent_page_itemclass. Below is the final code and you can find a working example here.