Reputation: 5523
I have a navigation animation that is being applied to elements with the "js" class - via a css background. I don't want this animation to occur on the link for the current page (a class "current" is being echo'd out by PHP to the current page).
So basically the page your on (current page) link in the main nav will have a class of current, the others a class of js - and get the animation. How do apply that logic in a funciton? I can do it via css background but want to do it in js. Here is working js used in combination with css for desired look:
$(function() {
$("ul#mainNav li a").addClass("js");
$("ul#mainNav li a").hover(
function () {
$(this).stop(true,true).animate({backgroundPosition:"(0 0)"}, 200);
$(this).animate({backgroundPosition:"(0 -5px)"}, 150);
},
function () {
$(this).animate({backgroundPosition:"(0 -130px)"}, 200);
}
);
});
What I'm trying to no avail:
$(function() {
if($("ul#mainNav li a").hasClass("current")) {
//do nothing
} else {
$(this).addClass("js")
}
//rest of animation function
});
});
Upvotes: 0
Views: 2170
Reputation: 35
For anyone looking at this to us on a live event (such as .live('click', )
$("ul#mainNav li a").not(".current").addClass("js");
GolezTrol's '.not' answer (above) although effective usually can fall down on live events.
So I would suggest using the answer supplied by Chris G. (below)
if(! $("ul#mainNav li a").hasClass("current")) {
$("ul#mainNav li a").addClass("js")
}
I hope this is useful to someone as it may save them some time trying to figure out what they have done wrong (as it was in my case)
Upvotes: 0
Reputation: 5290
You could use the :not selector provided by jQuery to do it more succinctly:
$("ul#mainNav li a:not(.current)").addClass("js")
Upvotes: 1
Reputation: 707158
There are several ways to approach this. If you need the selector you have for other things, you can do it like this:
$(function() {
$("#mainNav li a").each(function() {
if (!$(this).hasClass("current")) {
$(this).addClass("js")
}
});
//rest of animation function
});
If you don't need that whole selector for other things, then you can do it more simply like this:
$("#mainNav li a").not(".current").addClass("js");
Note, I've removed the ul from the start of your main selector as it is not required since ids are unique.
Upvotes: 2
Reputation: 3981
if(! $("ul#mainNav li a").hasClass("current")) {
$("ul#mainNav li a").addClass("js")
}
The other answer is better, but this is how your if statement would work if you insisted to do it that way. $(this) only works in the correct scope. You're confusing its usage for when you are using a closure like:
$('a').each(function(){ $(this).stuff(); });
Upvotes: 1
Reputation: 116100
$("ul#mainNav li a").not(".current").addClass("js");
Your if
should work too, but you mix up this
and $("ul#mainNav li a")
.
Upvotes: 5