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?
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?
3 Answers
Reset to default 5var x = 20;
$('#my_id').css('margin-top', function(index, value) {
if (isNaN(parseInt(value)))
return x;
return parseInt(value) + x
});
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.
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; });