Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Animate Removal of CSS Property

Tags:

jquery

css

I'm visually "collapsing" some DOM elements using jQuery (by shrinking their width to 0px and fading them out) like this:

$(".slideoutmenu").animate({ width: 0, opacity: 0 }, function() { $(this).hide(); }); 

The width of these elements can vary, but the document is properly laid out through CSS without setting a specific width.

Normally, to re-show these elements I could simply do something like this:

$(".slideoutmenu").stop().show().css({ width: '', opacity: 1 });

However, I'd like to animate these elements in reverse (fade in, and expand).

Normally I'd do this with something similar to this:

$(this).children(".slideoutmenu").stop().show().animate({ width: 250, opacity: 1 });

So this is the obvious attempt:

$(this).children(".slideoutmenu").stop().show().animate({ width: "", opacity: 1 });

But this doesn't work.

Ultimately, the problem here is the fixed "250" number in the example above. This doesn't work because the widths are variable. I need to combine the result of using the empty string in the css setter and "animate"... but I can't figure out how to do this. I've tried replacing the "250" with 'undefined', 'null', '-1', '', and I've searched Google... to no avail.

I understand I can probably do some measurement trickery with the element hidden from the user - but I can't imagine this isn't a fairly common issue - so I'm hoping there is a "standard" way to do this, or that it's built in some how and I just don't know about it.

Thanks for reading.

FOLLOW UP:

Based on Michael's kind response, I put together a small quick-and-dirty plugin so I can accomplish this inline. (maybe someone can expand upon the plugin idea and make it better)

Here is the plugin:

(function( $ ){

  $.fn.cacheCss = function( prop ) {  

    return this.each(function() {

      var $this = $(this);


        if (prop instanceof Array)
        {
            for (var pname in prop)
            {
                if ($this.data('cssCache-' + prop[pname]) != undefined)
                    continue;

                $this.data('cssCache-' + prop[pname], $this.css(prop[pname]));
            }
        }
        else
        {
            if ($this.data('cssCache-' + prop) != undefined)
                return $this;

            $this.data('cssCache-' + prop, $this.css(prop));
        }

        return $this;

    });

  };


  $.fn.revertCss = function(settings, prop, animated) {  

    if (settings == null)
        settings = {};

    return this.each(function() {

      var $this = $(this);

        if (prop instanceof Array)
        {
            for (var pname in prop)
            {
                if ($this.data('cssCache-' + prop[pname]) != undefined)
                    settings[prop[pname]] = $this.data('cssCache-' + prop[pname]).replace(/px$/, "");               
            }
        }
        else
        {
            if ($this.data('cssCache-' + prop) != undefined)
                settings[prop] = $this.data('cssCache-' + prop).replace(/px$/, "");
        }

        if (!animated)
          return $this.css(settings);

        return $this.animate(settings);

    });

  };

})( jQuery );

And here is how I was able to modify my code to use it:

The origional line which set the css property:

$(".slideoutmenu").animate({ width: 0, opacity: 0 }, function() { $(this).hide(); }); 

was replaced by:

$(".slideoutmenu").cacheCss('width').animate({ width: 0, opacity: 0 }, function() { $(this).hide(); }); 

Now, ".cacheCss('width')" caches the value of the css property before I perform my animation.

And the line I had to "undo" those changes:

$(this).children(".slideoutmenu").stop().show().animate({ width: 250, opacity: 1 });

was replaced by this:

$(this).children(".slideoutmenu").stop().show().revertCss({ opacity: 1 }, 'width', true);

Now, ".revertCss(...)" will use the cached settings to revert my width property (animated!)

I made the plug accept arrays as well, so you could do this too:

.cacheCss(['width', 'height'])

and then:

.revertCss(null, ['width', 'height'], true)

the third parameter controls whether or not the revert is animated or not.

If you have other properties you want to animate at the same time (like i did with "opacity" in the example earlier) you can pass them in as the first parameter just like you would pass an object into the .animate() function.

I'm sure the plug could be GREATLY improved, but I thought it might be nice to throw it out there anyways.

Also, one more point - I had to replace spurrious "px" at the end of the css values... again, I'm sure there is probably a better way of doing that, but I just used a standard regex.

like image 457
Steve Avatar asked Jun 10 '11 00:06

Steve


People also ask

Can the animate () method be used to animate any CSS property?

The animate() method is an inbuilt method in jQuery which is used to change the state of the element with CSS style. This method can also be used to change the CSS property to create the animated effect for the selected element.

How to animate CSS in jQuery?

The jQuery animate() method is used to create custom animations. Syntax: $(selector).animate({params},speed,callback); The required params parameter defines the CSS properties to be animated.

How to stop jQuery animate?

The jQuery stop() method is used to stop an animation or effect before it is finished. The stop() method works for all jQuery effect functions, including sliding, fading and custom animations. Syntax: $(selector).

What is the use of the animate() method in jQuery?

The animate() method performs a custom animation of a set of CSS properties. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect. Only numeric values can be animated (like "margin:30px").


1 Answers

You could store the width of the element pre-animation using jQuery data:

$(".slideoutmenu").each(function(){
    $(this).data('width', $(this).css('width'));
    $(this).animate({ 
        width: 0, 
        opacity: 0 
    }); 
});

$(".slideoutmenu").each(function(){
    $(this).children(".slideoutmenu").stop().animate({ 
        width: $(this).data('width'), 
        opacity: 1 
    });
});
like image 99
Michael Robinson Avatar answered Sep 22 '22 07:09

Michael Robinson