Andrii Abramov
Andrii Abramov

Reputation: 10751

jQuery returns the same opacity

I am trying to use simple animation with opacity css property:

$('#testAnimation').click(function (event) {
    if ($(this).css('opacity') == 0) {
        $('#animationTarget').animate({opacity: 1}, 'slow');
    } else {
        $('#animationTarget').animate({opacity: 0}, 'slow');
    }
});

The first time, element is successfully hidden. But when I click button second time, $(this).css('opacity') returns value "1".

Debugging in browser clearly says that opacity is 0.

Can someone explain this behavior?

Upvotes: 3

Views: 82

Answers (4)

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

Checking for $(this) within your click event handler you will refer to the element $('#testAnimation')

Instead you should check for $('#animationTarget') and also you can 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');
});

Upvotes: 0

Fabrizio Mazzoni
Fabrizio Mazzoni

Reputation: 1909

Try using .fadeIn() and .fadeOut() to achieve what you are doing. Less code to write. have a look at the :visible part as I don't remember if it is the correct syntax!

$('#testAnimation').click(function (event) {
  if ($(this).is(':visible') {
      $(this).fadeOut();
  } else {
      $(this).fadeIn();
  }
});

Upvotes: 1

Erazihel
Erazihel

Reputation: 7605

You are checking the opacity of this and changing the one of the #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');
  }
});

Upvotes: 3

Andrii Abramov
Andrii Abramov

Reputation: 10751

Well, this was my fault.

For anyone who faces similar issue, be sure that you are checking property of the desired element:

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

Should be replaced with:

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

Upvotes: 1

Related Questions