Question

I have a really simple animation. I want div.box at (right:10px) to move to left:10px when it is clicked. The container width could be variable, so it's crucial that the left edge of the div always animates to left:10px. With the code below this does not work. I've successfully hacked a way for it to move by obtaining the width of <body> when the div is clicked and doing some calculations, but it and breaks down after the browser is resized. Is there a better way to accomplish this? I suspect the problem with the JS below stems from the fact that the position of div.box, right: 10px;, is not being removed after the JS runs.

JSFIDDLE: http://jsfiddle.net/5GL5r/15/

CSS

.box {
    width:100px;
    height:50px;
    background: red;
    position: absolute;
    right: 10px;
    top: 0;
    bottom: 0;
    margin: auto;
}

JS

$(".box").click(function() {
    $(this).animate({left:"10px"});
});
Was it helpful?

Solution

Animating on the right property (as you already tried) and afterwards setting the left property might work for you. I will only 'break' if you resize your window during animation, although after the animatin is finished everything will look ok again.

$(".box").click(function() {
    var parentWidth = $(this).parent().width();
    var newRight = parentWidth - $(this).width() - 10;
    $(this).animate({right: newRight}, function() {
        // On animation finish:
        $(this).css('right', 'auto')
               .css('left', '10px');
    });
});

JSFiddle

(Edit, after first comment):

JQuery.animate calculates the step-size at the beginning. So if you work with pixels that won't work well if your parent-div resizes during the animation. If you however work with percentages it will work. Following might be an quite ugly hack:

New CSS (give wrap a padding of the width of your box, and box an left margin of 100%)

.wrap {
    height: 50px;
    background: #aaa;
    position:relative; 
    top:0;
    left:0;
    padding: 10px 110px 10px 10px;
}

.box {
    width:100px;
    height:50px;
    background: red;
    margin-left: 100%;
}

And animate the left-margin to 0% using javascript:

$(".box").click(function() {
    $(this).animate({
        marginLeft: '0%'
    });
});

JSFiddle (I've given it a very slow speed, so you can try resizing the frame)

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