Reputation: 12495
I have a string value in percent unit that will be assign to height but before assigning I need to deduct another height which got by top() the output result is NaN
, My code is as below:
var valHeight = "50%";
var result = valHeight - $("#item").css("top");
$("#AnotherItem").height(result);
as valHeight
is string and percent and height is pixel the result will be NaN
. How may I solve that issue? the valHeight
is percent but top value is pixel. I need to have my result as percent
Let's clarify more:
I want to use calc function of CSS and I guess the below code is correct:
$('#AnotherItem').css('height', valHeight).css('height', '-='+itemOffsetTop);
the only problem is I want to use subtracted value in animate function.
Upvotes: 1
Views: 2656
Reputation: 707238
I see two issues with your code:
valHeight
is a string, not a number. It needs to be a number before using it in a math operation. .top()
from. Perhaps you meant to use .offset().top
?Example:
var valHeight = 50;
var result = valHeight - $("#item").offset().top;
$("#AnotherItem").height(result + "px");
Now, you modified your question to use 50%
and it doesn't really make sense. If you want the result to be 50% of $("#item").offset().top
, then you could use something like this:
var valHeight = 0.5;
var result = $("#item").offset().top * valHeight;
$("#AnotherItem").height(result + "px");
Upvotes: 2
Reputation: 13679
First
valHeight
is a string you need to convert that to number.
var varlHeight = parseInt("50px");
Second
Your $("#item").top()
is invalid, use this instead.
$("#item").offset().top
Putting them together
var valHeight=parseInt("50px");
var result= valHeight - $("#item").offset().top;
$("#AnotherItem").height(result);
Update
Since you've updated your post with a '50%' value. How about doing this kind of approach instead.
var valHeight="50%";
var itemOffsetTop = $("#item").offset().top;
$('#AnotherItem').css('height', valHeight).css('height', '-='+itemOffsetTop);
Upvotes: 2
Reputation: 133403
.offset()
as there is no method as .top()
in jQueryGet the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.
valHeight
should be a numberCode
var valHeight = 50; //Or, parseInt("50px")
var result = valHeight - $("#item").offset().top;
$("#AnotherItem").height(result + "px");
Upvotes: 1