Reputation: 371
I have two separate ULs as menus. I'd like the second menu items to change text color when I hover the first menu items. Maybe a solution where the links with the same href as the link you hovered change css class? How could I do that with jQuery?
<ul class="firstMenu jQueryHover">
<li><a href="href1">bla</a></li>
<li><a href="href2">bla2</a></li>
</ul>
<ul class="secondMenu">
<li><a href="href1">blabla (same href as firstMenu item you hovered changes this elements css class)</a></li>
<li><a href="href2">blabla (same href as firstMenu item you hovered changes this elements css class)</a></li>
</ul>
Upvotes: 1
Views: 3218
Reputation: 165951
If you want to affect all the links with the same href
, including the one that was hovered over:
$("a").hover(function() {
$("a[href='" + $(this).attr("href") + "']").addClass("yourClass");
}, function() {
$("a[href='" + $(this).attr("href") + "']").removeClass("yourClass");
});
This makes use of the attribute name selector, to find all links with the same href
as the currently hovered link.
Here's a working example.
If you wanted to make it so only the other links change (and not the hovered one) then you can make use of the jQuery not
method to exclude the hovered element. It's not clear from your question whether you want all links with the same href
to change, or all other links but not the currently hovered one.
$("a").hover(function() {
$("a[href='" + $(this).attr("href") + "']").not(this).addClass("yourClass");
}, function() {
$("a[href='" + $(this).attr("href") + "']").not(this).removeClass("yourClass");
});
Upvotes: 3
Reputation: 18344
Should be simple:
$(".jQueryHover a").hover(function(){
if($(this).hasClass("hovering"))
{
$(this).removeClass("hovering");
$('a[href="'+$(this).attr('href')+'"]').removeClass("hovering");
}
else {
$(this).addClass("hovering");
$('a[href="'+$(this).attr('href')+'"]').addClass("hovering");
}
});
Upvotes: 2
Reputation: 20364
To change all anchor tags with the same href
$("a").hover(function() {
$("a[href='" + $(this).attr("href") + "']").addClass("hover-class-name");
}, function() {
$("a[href='" + $(this).attr("href") + "']").removeClass("hover-class-name");
});
However, I can not see why you want to have two links with the same href on the page? Have you thought about using class names rather than the href to link the anchors?
Upvotes: 2
Reputation: 76870
You could do:
$('.firstMenu ').hover(function(){
var href = $(this).attr('href');
$('.secondMenu a[href='+href+']').addClass('newClass');
},
function(){
var href = $(this).attr('href');
$('.secondMenu a[href='+href+']').removeClass('newClass');
}
);
Upvotes: 1