views:

39

answers:

2

Greetings,

I am changing the width of an element which serves as a bar , and that works. However I can't make it so that it animates it in the opposite direction. I tried putting - in front of bar_width but to no avail. Width will be dynamically calculated it's just that I want the direction to go to the left rather than to the right like so <------- not ----------->

var bar_width=$(this).css('width') ;
$(this).css('width', '0').animate({ width: bar_width }, queue:false,duration:3500,easing: easing});
A: 

Instead of 0 you can use "toggle" as the parameter, like this:

$(this).animate({ width: "toggle" }, queue:false, duration:3500, easing:easing});

"toggle" will animate from it's full width to 0, and the reverse next time.

Nick Craver
Hi thanks for your time. The problem is that "toggle" goes to the right then goes back to the left. Basically I want it to go to the left right away.
Marin
@Marin - If you want the left direction to be instant you can give that call a `duration: 0`, is that what you're after?
Nick Craver
Not quite instantenous but somewhere close to Pat's solution.
Marin
@Marin - If you want the animation quicker, whatever you feel comfortable with, just lower the `duration`...are you going for a different effect than that?
Nick Craver
Nick something similar to Pat's but I still can't manage to work like that because my width will change and I can't set up my css beforehand.
Marin
A: 

You could animate it from right to left by animating both the margin-left and width of the element at the same time:

CSS

#bar {
    margin-left: 100px;
    height: 10px;
    width: 0;
    background: red;
}

jQuery

$('#bar').animate({
    marginLeft: 0,
    width: 100
});

In action here.

Alternative, if your element is positioned absolutely you could animate the left property and width at the same time.

Pat
Thanks for providing the link. I still can't grasp how changing the margin forces the width to go to opposite direction.
Marin
It doesn't but it makes it look that way :) In html/css the default is to grow in width from left to right (it may be different if you change your reading direction, but I've never experimented). Anyway, by changing the margin what happens is that the element continues to grow from left to right, but at the same time it's also moving left. This makes it appear to grow right to left.
Pat
Hi Pat, thanks a lot for your code. The problem is that width is dynamic and the trick is based on knowing width beforehand. It works perfectly if you set it to width 100 , but my width will change. I'll see if there's a workaround and I'll post it if successful.
Marin
At some point you must know the final width you're animating to correct? If that's the case, just before you begin animating the width set the `margin-left` of the element to this dynamic width.
Pat
Correct,I thought about it but was hesitant :P - Cheers
Marin