1

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 3

5
var x = 20;
$('#my_id').css('margin-top', function(index, value) {
    if (isNaN(parseInt(value)))
        return x;

    return parseInt(value) + x
});
Sign up to request clarification or add additional context in comments.

3 Comments

This will fail if parseInt(value) returns NaN. You should add some sort of protection against that possibility.
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.
...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.
2
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.

3 Comments

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.
All valid points. Has parseInt always behaved like that? I must be thinking of my ie6 javacript days.
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)
1

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; });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.