Nick Mehrdad Babaki
Nick Mehrdad Babaki

Reputation: 12495

Converting Percent value to pixel in JavaScript or JQuery

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

Answers (3)

jfriend00
jfriend00

Reputation: 707238

I see two issues with your code:

  1. valHeight is a string, not a number. It needs to be a number before using it in a math operation.
  2. It's also not clear where you're getting .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

Robin Carlo Catacutan
Robin Carlo Catacutan

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

Satpal
Satpal

Reputation: 133403

  1. You need to use .offset() as there is no method as .top() in jQuery

Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.

  1. valHeight should be a number

Code

var valHeight = 50; //Or, parseInt("50px")
var result = valHeight - $("#item").offset().top;
$("#AnotherItem").height(result + "px");

Upvotes: 1

Related Questions