Thomas
Thomas

Reputation: 34218

jQuery toggle opacity with animate function

i wrote a jquery function and from there i try to toggle opacity with animate function but my code is not working. can anyone tell me where is the fault. thanks

            jQuery.fn.blindToggle = function (speed, easing, callback) {
            var _opacity = 0;
            var h = this.height() + parseInt(this.css('paddingTop')) + parseInt(this.css('paddingBottom'));
            $(this).toggle(function () {
                _opacity = 0;
            },
            function () {

                _opacity = 1;
            });
            alert(_opacity);
            return this.animate({ opacity: _opacity,
                marginTop: parseInt(this.css('marginTop')) < 0 ? 0 : -h
            }, speed, easing, callback);
        };

Upvotes: 1

Views: 8937

Answers (3)

Paweł Brewczynski
Paweł Brewczynski

Reputation: 2743

jQuery has sweet function

.fadeToggle()

Documentation.

Upvotes: 0

Renato Zannon
Renato Zannon

Reputation: 30011

jQuery's animate has a shortcut for what you're trying to do:

$(this).animate({"opacity": "toggle"});

Then you don't need to implement that logic yourself.

Upvotes: 7

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

toggle only works for element attributes, not for var values. This case you can simple do the following.

_opacity = _opacity == 0 ? 1 : 0;

Demos:

Upvotes: 1

Related Questions