Reputation: 609
I have this:
HTML:
<p class="Link"><a href="...">Test1</a></p>
<p class="Link"><a href="...">Test2</a></p>
<p class="Link"><a href="...">Test3</a></p>
jQuery
$(document).ready(function() {
$('.Link').hover(function() {
$('.Link a').css('color', 'black');
}, function() {
$('.Link a').css('color', 'white');
});
});
First of all, I need to change the anchor color when the mouse hovers over the paragraph, not just the anchor. Secondly, I need to do this without creating a unique id for each paragraph or anchor. With the code as it is, it changes the color for all three anchors tags. I only want it to change the color on the anchor contained within the paragraph I am currently hovering over. Is this possible?
Thanks!
Upvotes: 2
Views: 1297
Reputation: 322492
You need to use this
which refers to the specific element that received the event.
$(document).ready(function() {
$('.Link').hover(function() {
// Get the <a> element from within the context of
// the element that received the event, represented
// by "this"
$('a',this).css('color', 'black');
}, function() {
$('a',this).css('color', 'white');
});
});
Doing:
$('a',this).css('color', 'black');
is effectively the same as doing:
$(this).find('a').css('color', 'black');
Of course, you could always accomplish this using purely CSS.
EDIT:
If all you're doing is changing some CSS attributes, you don't really need javascript.
To use a purely CSS approach, do this:
.Link a {
color: black;
}
.Link a:hover {
color: white;
}
Because you're doing this on an <a>
element, it is supported on IE6. Starting with IE7 (and most other browsers) you can use the same technique on other elements too.
Upvotes: 1
Reputation: 13691
You can use the selector $(this) inside the event to quickly refer to the element which is hovered over. After that you can use .find() to find any elements inside it.
Code:
$(document).ready(function() {
$('.Link').hover(function() {
$(this).css('color', 'black');
$(this).find("a").css('color', 'black');
}, function() {
$(this).css('color', 'white');
$(this).find("a").css('color', 'white');
});
});
Upvotes: 0
Reputation: 17831
$(this).find("a").css("color", "black");
should do the trick.
The problem is, that ".Link a" matches ALL anchors that are in a paragraph. You probably should read into CSS again with that kind of misunderstanding!
Upvotes: 0