user2066880
user2066880

Reputation: 5024

Make element collapse with jQuery's animate()

I'm experimenting with an animation that makes an inline html element collapse on itself (all the elements move to the center). The way I'm approaching it is very clunky and does not work as the width of the element changes.

Here is my attempt: http://jsfiddle.net/JFVxX/1/

HTML

<p id="one">1</p> &times; <p id="two">2</p>

CSS

p {
    display: inline;
    position:relative;
}

JS

$(document).ready(function() {
    $('#one').animate({
        left:'+=10'
    });
    $('#two').animate({
        right:'+=10'
    });    
});

Upvotes: 0

Views: 130

Answers (1)

Brigand
Brigand

Reputation: 86270

Demo

To position them based on their size, ask for their size. My formula for w / 2 + 10 is valid for when there is exactly 10px between the right edge of the first element, and the left edge of the second.

<p id="three">12345</p> &times; <p id="four">78910</p>
$('#three').animate({
    left:'+=' + ( $('#three').width() / 2 + 10 )
});
$('#four').animate({
    right:'+=' + ( $('#four').width() / 2 + 10 )
});    

It goes from this,

uncollapsed text

to this,

collapsed text

Upvotes: 1

Related Questions