jqueryjquery-animatewidthtoggleouterwidth

jquery set div width to other div's width after animation


I'm animating a div to be wider, after the animation I want to set the width of a following list to be the exact same with of the newly animated div, and move this to be under it.

Oddly, when resizing, it only resizes to a small width, once clicked again it will be the wanted size for a millisecond. This might not be unclear.

$('#LoginButton').click(function(){
  $('.username').stop(true,false).animate({width:'toggle'});
  $("#profilesettings").delay(220).toggle(300);
  $("#profilesettings").width( $("#LoginButton").outerWidth(true) );
});

Here's a Fiddle

So, I'd like the list that appears to be the width of the entire image + name bar and I'd like to move it exactly under it.

Thanks!


Solution

  • You can use an anonymous callback function along with the animate call, so that your menu appears once the clicked element has finished expanding. That way you will get the accurate width. You can then make it display underneath by setting clear:both;.

    The resulting code looks something like...

    $('#LoginButton').click(function(){
        //$('.username').stop(true,false).animate({width:'toggle'});
        $('.username').animate({
                width : 'toggle'
        }, 1000, 'swing',function(){
            var newWidth = ($('.username').width());
            $("#profilesettings").width(newWidth).css({
                clear:'both',
                'margin-top':0
            });        
            $("#profilesettings").toggle(300);
        });//end anonymous funciton            
    });//end click funciton
    

    I specified a 1 second delay, and added 'swing' easing as well. These are optional and you could use your original animate code if you prefer.

    here is your updated fiddle http://jsfiddle.net/CTms3/7/

    An alternative approach would be to animate the parent container, so that both the button and list expand at the same time..

    Hope this info helps.