JQuery returns the same opacity
I am trying to use a simple animation with opacity
a css property:
$('#testAnimation').click(function (event) {
if ($(this).css('opacity') == 0) {
$('#animationTarget').animate({opacity: 1}, 'slow');
} else {
$('#animationTarget').animate({opacity: 0}, 'slow');
}
});
The element is hidden the first time. But when I click the button a second time it $(this).css('opacity')
returns a value "1"
.
Debugging in the browser clearly states that opacity
- 0
.
Can anyone explain this behavior?
source to share
You check opacity
of this
and change one of #animationTarget
.
This should do it:
$('#testAnimation').click(function (event) {
if ($('#animationTarget').css('opacity') == 0) {
$('#animationTarget').animate({opacity: 1}, 'slow');
} else {
$('#animationTarget').animate({opacity: 0}, 'slow');
}
});
source to share
Try to use .fadeIn()
and .fadeOut()
to achieve what you are doing. Less code to write. let's look at the part :visible
as I don't remember if this is the correct syntax!
$('#testAnimation').click(function (event) {
if ($(this).is(':visible') {
$(this).fadeOut();
} else {
$(this).fadeIn();
}
});
source to share
By checking $(this)
in your click event handler you will be referring to the element$('#testAnimation')
Instead, you should check $('#animationTarget')
and also refactor your code like this:
$('#testAnimation').on('click', function (event) {
var $animationTarget = $('#animationTarget'),
opacity = $animationTarget.css('opacity') == 0 ? 1 : 0;
$animationTarget.animate({opacity: opacity}, 'slow');
});
source to share