What I am trying to do is, when I hover over a link, make its right border change colour as well as make the previous link's border change colour.
<div id="navbar">
<ul>
<li><a href="#">News</a></li>
<li><a href="#">Gigs</a></li>
<li><a href="#">Gallery</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">Social</a></li>
</ul>
</div>
And here's the JavaScript:
$("li a").hover(function() {
$(this).animate({
color: '#0099FF',
borderRightColor: '#0099FF'
}, 500);
$(this).prev().animate({borerRightColor: '#0099FF'}, 500);
}, function() {
$(this).animate({
color: '#FFFFFF',
borderRightColor: '#FFFFFF'
}, 500);
$(this).prev().animate({borerRightColor: '#FFFFFF'}, 500);
});
Any help or advice would be appreciated, thanks!
The selector li a
selects each <a>
element. .prev()
selects the previous sibling, not the "previous element in the collection," and there is no previous element for the <a>
s because they have no siblings, only parents. Try this instead:
$(this).closest('li').prev().children().animate(...);
Also, you've used borerRightColor
instead of borderRightColor
.
From the documentation for .prev()
:
Description: Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.
The links are not siblings.
$("li").hover(function() {
$(this).children().animate({
color: '#0099FF',
borderRightColor: '#0099FF'
}, 500);
$(this).prev().children().animate({borerRightColor: '#0099FF'}, 500);
}, function () {
$(this).children().animate({
color: '#FFFFFF',
borderRightColor: '#FFFFFF'
}, 500);
$(this).prev().children().animate({borerRightColor: '#FFFFFF'}, 500);
});
Here's a demo on jsFiddle . I put the hover on the <li>
while I was at it so you aren't traversing all over the place.
The this
context refers to the <a>
element being hovered, not the <li>
. The <a>
element doesn't have a previous sibling.
Use the parent
method to access the <li>
:
$(this).parent()......
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.