Question

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 ?

Was it helpful?

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

OTHER TIPS

If I understand correctly... this can be done with simple CSS Transitions.

HTML:

<div class="div1">
    <div class="div2"></div>
</div>
<a href="#" id="button">Animate</a>

CSS:

div {
  -webkit-transition: width 1s ease;
  -moz-transition: width 1s ease;
  -o-transition: width 1s ease;
  transition: width 1s ease;
  float:right;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
.div1 {
    border: 1px solid #ccc;
    padding: 10px 10px 0 50px;
    float:right;
    width: 400px;
}
.div2 {
    border: 1px solid red;
    padding: 10px;
    margin-bottom: 10px;
    height: 100px;
    width:250px;
}
.no-padding {
    width: 600px;
}
.adjust-width{
  transition-delay: .8s;
  width:100%;
}

JQUERY:

$("#button").click( function() {
    $(".div1").toggleClass("no-padding");
    $(".div2").toggleClass("adjust-width");
});

DEMO: http://jsfiddle.net/yinnette/VVe64/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top