tags:

views:

54

answers:

3

Given an element with unknown margin-left, how to increase its margin-left at a number say 100px?

For example:

assuming the original margin-left is 100px

the expected result is 100px + 100px thus 200px finally.

+1  A: 

A quick/terse way to do this:

$('#IDHere').animate({marginLeft: '+=100px'}, 0);​​​​​​​​​​​​​​​​​

Here's a quick example of this. The 0 makes this happen in a single frame, if you actually want to animate it, change the 0 to the number of milliseconds you want, like this.

Nick Craver
this is only work for animate, but i don't wanna animate it
Edward
@Relax - The `0` isn't an animation, it's a 1 frame CSS update, isn't it quicker to click the link and see this working than immediately dismissing it? That's a bad approach, and you'll miss out learning a lot of new things that way, just something to think about.
Nick Craver
I prefer with value change, but i think this way will also work and your idea is creative, :)
Edward
+1  A: 
$('#element-id').css('margin-left', function (index, curValue) {
    return parseInt(curValue, 10) + 100 + 'px';
});

curValue will include 'px' at the end, so you'll end up with NaN or 100px100px as your result without using parseInt first.

Matt
this is exactly what i want
Edward
A: 
$("p").css({marginLeft: function(index, value) {
    return parseFloat(value) + 100;
}});
artlung