2

Is it possible to use animate() to increase a div's width dynamically and display this in a variable?

I've tried several things, but the variable still displays the original width of the div (wich is zero) So it's not being updated.

HTML

<a href="#" id="button2">Add width</a>
<div id='content'></div>
<div id="msg"></div>

jQuery

$('#button2').click(function () {
    $('#content').animate({
        width: '+=40'
    }, 500);
});

var width = $('#content').width();
$("#msg").html(width);

Demo

So I would like to know how I can accomplish this. Should I write a update function for the variable or is there a more simple way?

Opoe
  • 1,337
  • 8
  • 30
  • 56
  • http://stackoverflow.com/questions/8279196/animate-jquery-event-handler-in-the-middle-of-animation – Andreas Aug 15 '13 at 06:57

4 Answers4

2

Take a look at documentation. You can provide a complete function in your animate function:

$('#content').animate({
        width: '+=40'
    }, 500, function () {
      var width = $('#content').width();
      $("#msg").html(width);
});

Alternatively, use overloaded method with two parameters (attributes and options):

$('#button2').click(function () {
    $('#content').animate({
        width: '+=40'
    }, {
        step: function () {
            var width = $('#content').width();
            $("#msg").html(width);
        }
    })
});

FIDDLE DEMO

Artyom Neustroev
  • 8,627
  • 5
  • 33
  • 57
1
$('#button2').click(function () {
    $('#content').animate({
        width: '+=40'
    }, 500, function() {
        var width = $('#content').width();
        $("#msg").html(width);
    });

});
Paul Nikonowicz
  • 3,883
  • 21
  • 39
0

Use animate callback..

Your code checks and updates the width only once - in the beginning. You must do it every time the animation updates the width of content. For that you could use the animate method's callback.

$('#button2').click(function () {
    $('#content').animate({
        width: '+=40'
    }, 500, function(){
        var width = $('#content').width();
        $("#msg").html(width);
    });
});

Callback is a function passed as the third parameter of 'animate' and it is called when the animation finishes.

Working fiddle: http://jsfiddle.net/7asv2/4/

Jithesh
  • 972
  • 4
  • 10
0

You can add a function which es called on any step of the animation

$('#content').animate({
        width: '+=40'
    }, {
        step: function (w) {
            msg.html(w);
        },
        duration: 500,
        easing: "linear"
    });

fiddle

Andreas
  • 21,535
  • 7
  • 47
  • 56