Reputation: 135
I am newbie to JQuery and I try to make some basic tricks with it. So basicly, I have simple navigation made of unordered list, and I want to change font color on currently mouseover-ed list item with JQuery, but I have problem because my JQuery script is changing font color of all list items, and I want to change font color of ONLY currently mouseover-ed list item, not all. I tried to get currently mouseover-ed list item, but I don't know how to implement it so that my JQuery change only that list item. Here are pictures:
What I currently have: https://i.sstatic.net/AhUrs.jpg
What I want: https://i.sstatic.net/1rTUV.jpg
Here is my JQuery code:
$(document).ready(
function(){
$('.nav1 ul li').mouseover(
function () {
var index = $( ".nav1 ul li" ).index(this);
$('.nav1 ul li a').css({"color":"white"});
}
);
$('.nav1 ul li').mouseout(
function () {
var index = $( ".nav1 ul li" ).index(this);
$('.nav1 ul li a').css({"color":"#6291d8"});
}
);
}
);
Here is my HTML:
<nav class="nav1">
<ul>
<li><a href="#">HOME</a></li>
<li><a href="#">SERVICES</a></li>
<li><a href="#">THERAPIES</a></li>
<li><a href="#">GALLERY</a></li>
<li><a href="#">BOOKING</a></li>
<li><a href="#">CONTACT</a></li>
<li><a href="#">ABOUT ME</a></li>
</ul>
</nav>
Upvotes: 1
Views: 1622
Reputation: 337560
There is no need for JS here. You can use the CSS :hover
psuedo class:
.nav1 ul li a {
color: #6291d8;
}
.nav1 ul li a:hover {
color: #FFF;
}
Upvotes: 1
Reputation: 207901
this
is a special word in JavaScript that refers to the element that triggers an event. In jQuery you can use $(this)
. So you can replaceyour code with:
$(document).ready(function () {
$('.nav1 ul li a').hover(function () {
$(this).css("color", "white");
}, function () {
$(this).css("color", "#6291d8");
});
});
Notice that I also changed the selector to '.nav1 ul li a'
. The anchors have their own default styling, so to override that you should target them, and not the parent list item. I also replaced your mouseover
and mouseout
with the hover
method as it saves a few characters. Finally, I used the more basic single property version of .css()
which also saves a few characters.
Upvotes: 1
Reputation: 4682
Why JQuery
?
use a:hover
in css
it is pretty cleaner.
Like:
.nav1 ul li a {
color: #6291d8;
}
.nav1 ul li a:hover{
color:white;
}
For all other links you can again use a
and a:hover
also a:active
will give you additional functionality.
Upvotes: 1
Reputation: 62488
Instead of:
$('.nav1 ul li a').css({"color":"white"});
and:
$('.nav1 ul li a').css({"color":"#6291d8"});
use:
$(this).css({"color":"white"});
$(this).css({"color":"#6291d8"});
if you wan to apply css on achor tag:
$(this).find("a").css({"color":"white"});
$(this).find("a").css({"color":"#6291d8"});
By using $('.nav1 ul li a')
you are changing all anchor tags css but but by using $(this)
will change the current clicked element css.
Upvotes: 2