I’m attempting to toggle the opacity of a link control by checking if the element it toggles on/off is visible or not using the “:visible” selector. I have the following markup:-
<div class='btns'></div>
<p class='text'>Hello world</p>
With this jQuery:-
var text = $('.text');
text.hide();
var btn = $('<a>', {
'href': '#',
'text': 'click me',
'click': function(e){
e.preventDefault();
text.slideToggle();
var opacity = text.is(':visible').length ? 1 : .5;
$('.btns').animate({
'opacity': opacity
});
}
});
$('.btns').append(btn);
The first time the link is clicked the link fades to half opacity correctly, but then the opacity doesn’t change on subsequent clicks. You can see this in action on jsFiddle.
Why does the “:visible” selector fail on further clicks? Is there a better approach to this?
Apologises if this has already been answered on here, but I’ve not been able to find an answer to my particular question.
If you really want to test the text’s property you can do this :
Be sure to test before you start animating, because the display will never be “none” while animating.
To understand better what properties to test, I suggest you (if you use chrome), to right click on the animated text, inspect element, then watch carrefully which style parameters are being changed live when you activate the toggle.