Reputation: 15
I can't seem to wrap my head around this: http://jsfiddle.net/pvyaL/
$(function () {
if (!$(this).hasClass('selected')) {
$('.navigation li').hover(function () {
$(this).find('a').attr('class', 'hovering');
},
function () {
$(this).find('a').attr('class', '');
});
};
});
Basically what I want, is to ignore the hover class change, if the element already has a specific class (in this case; 'selected').
What am I missing?
Upvotes: 0
Views: 139
Reputation: 437336
That code has several mistakes:
this
refers to the document, not on any li
element..attr
is a really bad choice -- addClass
, removeClass
and toggleClass
exist exactly for this purpose.In jQuery form, what you want is more like
$('.navigation li:not(.selected)').hover(
function () {
$(this).find('a').addClass('hovering');
},
function () {
$(this).find('a').removeClass('hovering');
});
If you want to make the script respond to changes in the selected
class dynamically another version would be the solution:
$('.navigation li').hover(
function () {
if(!$(this).hasClass('selected')) $(this).find('a').addClass('hovering');
},
function () {
if(!$(this).hasClass('selected')) $(this).find('a').removeClass('hovering');
});
Of course there is no reason to do this with jQuery; pure CSS will suffice:
.navigation li:not(.selected):hover a {
/* your styles go here */
}
The :not
selector is not supported by IE8, but if that is a problem you can work around it using the set/revoke trick.
Upvotes: 3
Reputation: 53
$(this)
is in your code 'nothing', look at http://jsfiddle.net/pvyaL/2/
I also changed this:
if (!$(this).find('a').hasClass('selected')) {
So the check is on the <a>
, not on the <li>
Upvotes: 0
Reputation: 388316
Try
$(function() {
$('.navigation').on('mouseenter', 'li:not(.selected)', function() {
$(this).find('a').attr('class', 'hovering');
}).on('mouseleave', 'li:not(.selected)', function() {
$(this).find('a').attr('class', '');
})
});
or
$(function() {
$('.navigation li').hover(function() {
if (!$(this).hasClass('selected')) {
$(this).find('a').attr('class', 'hovering');
}
}, function() {
if (!$(this).hasClass('selected')) {
$(this).find('a').attr('class', '');
}
});
});
Upvotes: 0