Reputation: 9466
I have a navigation with an empty div in each anchor tag that I am styling on hover.
html
<li><a href="#events">SPECIAL EVENTS <div></div></a></li>
css
a:hover div, a:active div{
color: $black;
height: 1px;
background-color: $black;
width: 100%;
margin-top: 5px;
}
I also have a active class that I am attaching on click with some js. This is currently working correctly.
var currentDiv;
function addSelected(){
if(currentDiv !== undefined){
$(currentDiv).removeClass("active");
}
currentDiv = $(this).find('div');
$(currentDiv).addClass("active");
}
$(".menu a").click(addSelected);
What I am trying to do is attached that same active class based on the user scroll. I get most of it working, but I can't seem to figure how how to attached the class to the div, and not the anchor itself. Here is the js I'm working with.
js
// Cache selectors
var lastId,
topMenu = $("#desktop-nav"),
topMenuHeight = topMenu.outerHeight()+15,
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var item = $($(this).attr("href"));
if (item.length) { return item; }
});
// Bind to scroll
$(window).scroll(function(){
// Get container scroll position
var fromTop = $(this).scrollTop()+topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function(){
if ($(this).offset().top < fromTop){
return this;
}
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
menuItems
//.parent().removeClass("active")
//.end().filter("[href='#"+id+"']").parent().addClass("active");
.removeClass("active");
end().filter($("[href='#"+id+"']")).find('div').addClass("active");
console.log(id);
}
});
I think the part that I am trying to change is this
"[href='#"+id+"']").parent()
but everything I try is either not working or giving me errors.
EDIT
Here is the fiddle that I am trying to modify.
Upvotes: 0
Views: 113
Reputation: 932
Use children()
instead of parent()
or find()
Example:
if (lastId !== id) {
lastId = id;
// add/remove active class on div
menuItems
.children().removeClass("active")
.end().filter("[href='#"+id+"']").children().addClass("active");
}
Upvotes: 1
Reputation:
I assume you've tried...
"[href='#"+id+"']").parent().find('div')
and/or...
"[href='#"+id+"'].div"
...if so, are you able to add a class
or id
to the div
and target it that way?
Upvotes: 0
Reputation: 11
Try changing it to use find() like in your click handler:
"[href='#"+id+"']").find('div')
Upvotes: 1