1

I was trying to get the top position of the element and the margin-bottom value.
that worked:

var top = -$('elem').postion().top; // lets say its -54
var margin = $('elem').css('margin-top'); // lets say its 0

Bud I need to add these up for my animate function. so top+margin but jQuery gives -540 px but it need to return -54 px.. or when its negative it just gives -54-10px when I need -64 px.

Is there someting to get this fixed? I can't come up with it and it annoys me!

My code:

var top = -$('#id1').position().top;
var margin = $('.scrollable').css('margin-top');

var combine = top+margin;

$('.animate').animate({'margin-top' : combine});
1
  • the second one is a string (eg: "10px")... Commented Jan 16, 2012 at 15:20

3 Answers 3

6

Bud i need to add these up for my animate function. so top+margin but jQuery gives 540 p

css values are strings, so since one of your operands is a string, the + is being interpreted as a concatenation operator (54 + "0" = "540"), not an addition operator. (Details) To turn them into numbers, use parseInt(str, 10), e.g.:

// I believe `top` will already be a number; check and if not, use parseInt here too,
// e.g. var top = -parseInt($('#id1').position().top, 10);
var top = -$('#id1').position().top;

// This will definitely be a string that needs parsing; note that we're assuming
// here that the margin has been given in `px` units.
var margin = parseInt($('.scrollable').css('margin-top'), 10);

// Now this + is an addition, not a concatenation    
var combine = top+margin;

$('.animate').animate({'margin-top' : -combine});
Sign up to request clarification or add additional context in comments.

6 Comments

@Misiur isn't it the default conversion anyways?
Or use +str to convert to a number
Default is auto. Depends on what the string contains. So it will not be always 10. Can cause some nice bugs :).
@Xeon06: The default is "it depends on the string." Hence, always use it if you know the radix of the input.
Ah, actually, it should only parse as base 8 if the first character is '0'. MDC. However, as the page mentions it, it is better to always put it, since it's implementation can vary. Thanks for the tip guys.
|
3

It's because it returns the values as strings, and using the + operator on them concatenates. You can use parseInt to get a number from a string. It'll even work if there is a px suffix, though it will stop at that.

var top = $('elem').postion().top;
var margin = $('elem').css('margin-top');

var total = parseInt(top, 10) + parseInt(margin, 10);

1 Comment

Important use parseFloat or parseInt(int, 10);
0

Try this

var combine = parseInt(top) + parseInt(margin);

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.