Reputation: 1376
I'm trying to get a conditional statement to work that only runs if certain elements have a specific inline css style.
http://jsfiddle.net/zGg7Z/ HTML
<div>
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
</div>
JS
$(function(){
if ( $('.box').filter( function(){
return $(this).css('opacity') !== "0.4";
}) ) {
$('.box').on('click', function(){
$(this).siblings('.box').css("opacity", "0.4")
});
}
})
So when a box is clicked, its siblings fade to opacity: 0.4;
, but I don't want the fade function to run again as long as any of the boxes have that opacity. Thanks.
Upvotes: 0
Views: 378
Reputation: 78650
I agree with the answer of using a class. However, to explain why yours won't work... Your if
will always evaluate to true as filter
(even if empty) always returns a jquery object. Objects are "truthy". You would instead need .length
to check if the filter returned anything. On top of that, your filter condition is backwards as you would want to ensure that none of the elements have that opacity, instead you are checking that any element does not have the opacity. Also your numbers mismatch 0.4
and 0.3
and finally your if is outside of your click and should be inside.
Using your approach and only fixing the errors, you would have something like this:
$('.box').on('click', function(){
if($('.box').filter( function(){
return $(this).css('opacity') === "0.4";
}).length === 0 ) {
$(this).siblings('.box').css("opacity", "0.4")
}
});
Again, don't use this solution, go with one of the other answers using a class. I just thought it was worth explaining what was wrong with your code.
Upvotes: 1
Reputation: 27012
Generally, adding event handlers in conditionals is not what you want. Instead, always bind the handlers, then check a condition inside the handler. In this case though, I don't think you actually need a conditional at all. I think you're looking for something like this:
$('.box').on('click', function() {
$(this).removeClass('faded').siblings('.box').addClass('faded');
});
Upvotes: 0
Reputation: 17579
While it is totaly possible to create custom filter with jquery and test opacity css property in it, I would highly recommend to change your design and say create new css class, like
.glass {
opacity: 0.4;
}
And apply this class instead of inline property or together with it.
then
selector.filter('.glass')
to filter subset of elements from all elements you have.
Otherwise, use filter with function:
$( "div" ).filter(function( index ) {
return $( this ).css('opacity') == "0.4";
})
Upvotes: 1