seedy
seedy

Reputation: 91

JQuery Animate Opacity on Button Click

This seems like it would work but I'm probably not doing it the correct way. Not looking specifically for opacity/fade but any animation functions.

$('#button').click(function () {
    $(this).toggleClass('more');
    var txt = $('.more').is(':visible') ? '-' : '+';
    $(this).text(txt);
    if ($('#box').is(':visible')) {
        $('#box').animate({
            opacity: 0
        });
    } else {
        $('#box').animate({
            opacity: 1
        });
    }
});

FIDDLE

Upvotes: 1

Views: 110

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206669

LIVE DEMO

$('#button').click(function () {
    $(this).toggleClass('more');
    var vis = $(this).hasClass('more'); // boolean
    $(this).text( vis ? '-' : '+' );
    $('#box').stop().animate({opacity: vis ? 0 : 1 });
});

After you toggle a class, test the state, has class or not, making it a boolean (frue/false)
Than you can easily use that boolean value inside a
conditional operator (?:) (AKAternary operator) to do the truthy/falsy changes
of any desired method

example:

var iAmHappy = true;     // boolean
$('#mood').text( iAmHappy ? "Happy" : "Sad" )
          .css({ color:  iAmHappy ? "green" : "red" });

Upvotes: 2

Related Questions