The art of jQuery: Effortlessly animate the deletion of a CSS property

When using jQuery, I often "collapse" certain DOM elements by decreasing their width to 0px and fading them out. Here is an example:

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

The widths of these elements can vary, but the document layout is set up correctly through CSS without specifying a specific width.

To show these elements again, you could simply do something like this:

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

However, I want to animate these elements in reverse (fade in and expand).

Normally, I would use something like this:

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

So here's what I tried:

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

Unfortunately, this approach didn't work as expected.

The issue lies in the fixed "250" value used above. Since the widths are variable, I need to find a way to combine the result of setting an empty string for the width and animating it, but I haven't been able to figure it out. I've experimented with different values like 'undefined', 'null', '-1', '' without success.

I know I could potentially manipulate measurements while keeping the element hidden from the user, but I believe this must be a common problem and there should be a standard solution available, or perhaps it's built into jQuery in some way that I'm unaware of.

Thank you for reading.

FOLLOW UP:

After receiving helpful input from Michael, I created a simple plugin to achieve this functionality dynamically. Below is the plugin code:

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

Here is how I implemented the plugin with my existing code:

The original line that set the css property:

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

was replaced with:

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

The ".cacheCss('width')" now caches the value of the css property before starting the animation.

And when I needed to revert those changes:

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

was replaced with:

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

Now, ".revertCss(...)" uses the cached settings to revert the width property in an animated manner.

The plugin also accepts arrays, allowing you to cache multiple properties and then revert them together:

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

and later:

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

The third parameter specifies whether the reversion should be animated or not.

If you have other properties to animate alongside (e.g., 'opacity' as shown earlier), you can pass them in just like you would for the .animate() function.

I believe this plugin has room for improvement, but thought it might still be useful to share.

Lastly, I had to remove extra "px" at the end of the css values using a basic regex – there may be a more efficient method for doing this.

Answer №1

To preserve the original width of an element before animating it, you can utilize 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 
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for the ".filter" function to verify if the target contains multiple attributes?

I'm currently working on a checkbox filter setup and using Jquery's .filter to sort through some divs. Below is the snippet of Jquery code that I am using: $(document).ready(function(){ var checkboxes = $('div.filter-groups').find(&ap ...

What is the process for attaching an event handler to an element that is displayed after a button click?

I need some assistance with my JavaScript code. I have a page with two links, and when the second link is clicked, certain fields are displayed. I am trying to write an onkeyup() event handler for one of these fields, but seem to be missing something. Here ...

Creating visually appealing layouts with CSS floats and divs while ensuring responsiveness

As I work on bringing my vision to life, I'm experimenting with a mix of floats and divs, along with using a responsive image for the background and text. There's quite a bit involved in this process. 1. To start off, check out this example with ...

Looking for straightforward tips on parsing CSS code

Seeking advice on how to extract rules and property/values from a .css file or <style></style>. I am not in need of an elaborate parser, as the validity of selector text, property name, or value is not important. My main focus is ensuring that ...

Retrieve and manipulate the HTML content of a webpage that has been loaded into a

Hey, let's say I have a main.js file with the following code: $("#mirador").load("mirador.html"); This code loads the HTML content from mirador.html into index.html <div id="mirador"></div> I'm wondering if there is a way to chan ...

Comparing transition effects: scale, transform, and all

My goal is to apply transition effects to specific transform functions in CSS, such as scale(), while excluding others like translate(). Initially, I attempted the following code snippet: input:focus + label, input:not(:placeholder-shown) + label { tran ...

I'm having trouble getting Pycharm to locate my static files

My Pycharm is having trouble locating my CSS files. I've attached a screenshot showing the settings.py file, the directory where the .css file is located, and the error message from the terminal indicating a 404 error. Could someone please help me ide ...

What is the best way to utilize jQuery for deleting the final <li> within a <ul> element?

One of my web pages contains an unorganized list similar to this: <ul id="myList"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> How can I target the last ...

Interact with webpage dropdown menus using Python

I'm currently working on a Python script that interacts with a webpage, specifically , to retrieve a (DNA sequence in fasta format) file. The file is automatically downloaded when a user clicks on a dropdown menu. Here's the dropdown menu: Dow ...

Exploring the wonders of Bootstrap 3 panels and stylish floating images

Is it possible to create a responsive design using Bootstrap 3 panel along with a floating image positioned next to it? I want the panel to seamlessly fit into the available space, without overlapping the image. Can anyone provide guidance on achieving thi ...

Tips on aligning a span element at the center of an image without losing its mouseover

<div class="pic"> <img src="image.jpg" height="250"/> <span class="text" style="display:none">text here</span> </div> <scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </scrip ...

I am experiencing an issue with Safari where there is an unexpected rounded border appearing that

Upon inspecting the image, a slight border is visible behind the main border on Chrome and Firefox. However, Safari and iPhone display a rounded thin border instead. Can you help us understand why this discrepancy is happening and how we can remove it? P ...

The malfunctioning of JqueryUI icon with ui-state-error within a dialog

Currently, I am facing an issue with displaying a ninput and two spans containing jQuery UI icons in a jQuery UI dialog. The problem arises specifically when applying the ui-state-error to one of the spans. Interestingly, outside the dialog, the icons dis ...

Using jQuery to Decode the XML Document Containing National Threat Level Data

Recently, I've been experimenting with using jQuery to extract data from the DHS Threat Level found in their XML file. However, despite my efforts, I haven't been able to make it work. As a newcomer to Javascript and non-presentational jQuery, I& ...

What is the best way to implement a gradual decrease in padding as the viewport resizes using JavaScript

My goal is to create a responsive design where the padding-left of my box gradually decreases as the website width changes. I want the decrease in padding to stop once it reaches 0. For instance, if the screen size changes by 1px, then the padding-left sh ...

What is the process of importing a JSON file in JavaScript?

Is there a way to import a JSON file into my HTML form by calling $(document).ready(function (){});? The properties defined in the JSON file are crucial for the functionality of my form. Can anyone guide me on how to achieve this? ...

Centered Layout using HTML and CSS

Exploring the world of Ruby on Rails and HTML has been quite an adventure. Today's question veers away from RoR and focuses on HTML and CSS. As I attempt to center my body, a peculiar issue arises: Help me solve this problem here How can I align the ...

Jump to a specific section on a different page when the links are already equipped with anchors for smooth scrolling

My website has a menu on the home page that scrolls to specific id positions: <li><a href="#event-section">El evento</a></li> <li><a href="#asistentes-section">Asistentes</a></li> <li><a href="#cont ...

Is it possible to make multiple AJAX requests at the same time using AngularJS

I am looking to simultaneously send multiple AJAX requests. Here is the JS code I have: <a class='btn btn-success' ng-click='getDataajax()'>Re Check</a> app.controller('customersCrtl', function($scope, $http, $ti ...

Identify the name in the list by highlighting it when its content matches the text in a specific div id

I have an unordered list structured like this: <ul> <li id="projectrow_364"> <span>Forest</span> </li> <li id="projectrow_365"> <span>Life</span> ...