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?

+3


source to share


4 answers


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');
  }
});

      

+3


source


Well, it was my fault.

For those facing a similar issue, make sure you check the property of the required element:

if ($(this).css('opacity') == 0)

      



Should be replaced with:

if ($('#animationTarget').css('opacity') == 0)

      

+1


source


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();
  }
});

      

+1


source


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');
});

      

0


source







All Articles