Reputation: 1054
I'm struggling to find an answer to arguably one of the most basic jquery questions:
I would like the following to change the 'a' elements background color to blue (I expect it's a simple syntax issue)
[I am aware this is best done in CSS, but I am trying to learn jquery]
HTML:
<ul>
<li><a href="">Make</a></li>
<li><a href="">Me</a></li>
<li><a href="">Blue</a></li>
</ul>
CSS:
ul {
list-style:none;
}
li {
float:left;
}
a {
display:block;
text-decoration:none;
background-color:red;
height:40px;
width:100px;
margin-right:1px;
text-align:center;
line-height:40px;
color:white;
}
jQUERY:
$('a').hover(function() {
$('a').css('background-color', 'blue');
});
The jsFiddle is here: http://jsfiddle.net/liquidengine/jRM2K/2/
Upvotes: 0
Views: 413
Reputation: 19750
There's nothing in your jsFiddle. You just need to look at the code and try and understand what it's trying to do. In your example, whenever an a
is hovered, you are setting the color of all anchors to blue. Then you haven't tried to handle the mouseout event. Try something like this:
$('a').hover(function() {
// set background colour of the hovered anchor
$(this).css('background-color', 'blue');
}, function() {
// remove background colour when hovered off
$(this).css('background-color', '');
});
I know you said you don't want to use CSS because you want to learn jQuery, but this is a job for CSS. If you want to learn jQuery, try to build things that jQuery is required for. Because you should never, ever use jQuery to do this. And here's a hot tip: should you ever wish to change the colour of elements using jQuery (say, on click), at least use classes. Don't set the properties using jQuery. Example:
$('a').hover(function() {
$(this).toggleClass('hovered');
});
CSS:
a.hovered {
background-color: blue;
/* other styles here */
}
Upvotes: 2
Reputation: 100195
do:
$('a').hover(function() {
$(this).css('backgroundColor', 'blue');
});
Updated jsFiddle
Upvotes: 0