Search code examples
jquerycssdominline-styles

Transfer CSS value to DOM style attribute


enter image description here

Let assume that the #div1 has padding-left set to 50px. By pressing a specific button the padding is changing to 0 with an animation:

$('button').click(function(){
    $('#div1').animate({'padding-left':0}, 1000);
});

#div2 is a block so it will change its size together with #div1.

Now the heart of the matter, I want to transfer the #div2 width value to <div id="div2" style="width: [HERE]"></div> using jQuery. And then when #div1 will be animated the #div2 width will start to change its value in style attribute. I would like to see in browser developer tool how width of #div2 is changing. Something like this:

Button released:

`<div id="div2" style="width: 200"></div>`
`<div id="div2" style="width: 211"></div>`
`<div id="div2" style="width: 224"></div>`
`<div id="div2" style="width: 235"></div>`
`<div id="div2" style="width: 244"></div>`
`<div id="div2" style="width: 250"></div>`

After one sec:

`<div id="div2" style="width: 250"></div>`
`<div id="div2" style="width: 250"></div>`
`<div id="div2" style="width: 250"></div>`

How can it be done ?


Solution

  • The closest you can get is something like this, which calculates the auto width, then updates the DOM style property using jQuery's .attr

    $("button").click(function(){
        $("#div1").animate(
            {
                marginLeft: 0
            }, {
                step: function(){
                    $('#div2').width('auto');
                    var width = $('#div2').width();
                    $('#div2').attr('style', 'width: ' + width + 'px;');
                }
            }, 5000
        )
    });
    

    Overall this reallyisn't that useful because the browser inspector isn't an instantaneous change, so it jumps to the next values. Plus there is really no need for displaying the changes inline. If you want to display the change through another element (this shows immediate changes), then you can do so by using the same approach as my updated version of David Link's fiddle