I have the id of my element. I need to add a given value (determined by a variable in the javascript) to one of the element's css attributes. I.e. given an element id=my_id
how do I add x
to that element's margin-top
attribute?
views:
49answers:
3
+1
A:
One approach is to use jQuery's .animate()
method, but give it a duration of 0
. This allows you to send the +=
operator as a string, and concatenate the value of x
.
var x = 50;
$('#my_id').animate({marginTop: '+=' + x}, 0);
Another way would be to pass a function as the second parameter to jQuery's .css()
method. The return value will be the current value plus x
. This requires jQuery 1.4 or later.
var x = 50;
$('#my_id').css('margin-top', function(i,val) { return (parseInt(val) || 0) + x; });
patrick dw
2010-09-29 17:23:25
+5
A:
var x = 20;
$('#my_id').css('margin-top', function(index, value) {
if (isNaN(parseInt(value)))
return x;
return parseInt(value) + x
});
Björn
2010-09-29 17:23:31
This will fail if `parseInt(value)` returns `NaN`. You should add some sort of protection against that possibility.
patrick dw
2010-09-29 17:33:10
You're right, added base case condition.
Björn
2010-09-29 17:36:11
Björn - Unfortunately, with your edit it will now return the value of `x` 100% of the time. You'll never get to the second return statement because `isNaN(value)` will always evaluate to `true`. The reason for this is that when `margin-top` does have a value, the `value` parameter will give the size in `px` (like `10px`), which is not a number.
patrick dw
2010-09-29 18:05:08
...If jQuery always gives a `px` value, then your original `parseInt()` answer would work. I'd do some careful testing before relying on that, and then would still probably have a safety net.
patrick dw
2010-09-29 18:11:06
+1
A:
var inc = 20;
var mt = parseInt($('#my_id').css('margin-top').replace('px',''));
$('#my_id').css('margin-top',(mt+inc)+"px");
This assumes, of course, you always use px for margin-top values. I've used this reliably for quite some time.
methodin
2010-09-29 18:14:52
methodin - This will work, but you really don't need to do a `.replace('px','')`, because this will not interfere with `parseInt()`. Also you don't need to add `"px"` in your `.css()` call, since that is assumed when you pass an integer. Last thing is that you should consider caching the `#my_id` element instead of selecting it twice in a row.
patrick dw
2010-09-29 18:24:46
All valid points. Has parseInt always behaved like that? I must be thinking of my ie6 javacript days.
methodin
2010-09-29 18:32:26
methodin - I belive it is IE6 safe, but it wouldn't be a bad idea to double check. Certainly doesn't hurt much to have that safeguard in there. Just may be unnecessary. :o)
patrick dw
2010-09-29 18:36:32