Reputation: 14773
i have lots of divlayers with the class named ".current". depending on what the user does some of remove the class and some will get it again. this works fine, but what i want to is fire an event if only one div layer has the class ".current". how can i detect if only one element has the class current? for example
if ($('#div4').hasClass('.current')) {
alert("fire me something");
}
something like "is the only one" hasClass.
Upvotes: 0
Views: 647
Reputation: 179046
in your event callback, simply check the number of divs that have the current
class:
if ($('#div4').hasClass('current') && $('div.current').length === 1) {
...do stuff...
}
If you're only ever using current
on div
s, then you could just use $('.current').length === 1
.
Upvotes: 8
Reputation: 2566
See http://api.jquery.com/size/ or http://api.jquery.com/length/
$(".current").length
$(".current").size() *deprecated as of v1.8
Either will give you the count. Anytime you adjust the class check to see the count and fire the action if its 1
Upvotes: 0
Reputation: 21050
You could see how many instances of the class .current that there are by using length. e.g.
var mycount = $(".current").length;
alert(mycount);
Then do whatever you like with the result.
Upvotes: 0
Reputation: 185
You have error syntaxe! you should add an ")" for your condition. and dont use the calss selecotr (".") . that's will work:
if($('#div4').hasClass('current')){
alert("fire me something");
}
Upvotes: 0
Reputation: 5213
I "think" you could do:
if($('.current').length == 1) { //DO }
I believe the selector will return an array of the elements.
Upvotes: 0
Reputation: 37819
you should be able to use the css class as the selector and then get the length:
if($(".current").length == 1 ) {
alert('fire me something');
}
Upvotes: 0