Reputation: 515
I want to change the color of the li as red on mouse over. And keep the same color in click event also. I have the following list,
<html>
<body>
<ul>
<li>list1</li>
<li>list2
<ul>
<li>sublist1</li>
<li>sublist2</li>
<li>sublist3</li>
<li>sublist4</li>
</ul>
</li>
<li>list3</li>
<li>list4</li>
</ul>
</body>
</html>
list1
list2
sublist1
sublist2
sublist3
sublist4
list3
list4
If i click the list1, it color should be change into red, at the same time if i mouse over the other list it will be displayed as red. Its default color is black.
Upvotes: 1
Views: 17740
Reputation: 5399
// CSS: Create the highlight accessible with two classnames.
.highlight, .highlight_stay{
color:red;
}
Jquery
$(function(){
$('li').hover(function(){
$(this).addClass('highlight');
}, function(){
$(this).removeClass('highlight');
});
$('li').click(function(){
$(this).addClass('highlight_stay');
});
});
To remove the click color when a different li
is clicked change the last function to this:
$('li').click(function(){
$(li).removeClass('highlight_stay');
$(this).addClass('highlight_stay');
});
Upvotes: 5
Reputation: 3762
Mouse hover - css
li:hover {
color: red;
}
if you want it to be green only wen you click - css
li:active {
color: green;
}
if you want it to change color and remain in that color - JQuery
$("li").click(function (){
$(this).css("color","green")
});
however you might condider reading up on $("blah").addClass()
as it will help DOM load faster. Using css $(this).css("color","green")
"directly" on JQuery can slow things down as project gets bigger
Upvotes: 2
Reputation: 33315
Use css for that:
li:hover {
color:red;
}
And this is not recommended:
li:focus {
color: red;
}
JQuery
$('li').click(function(){
$(this).css('color','red');
});
Upvotes: 3