Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting width or height as percentage instead of pixels

I have elements with an external style of height with percentages. when I am trying to save the height as a variable to use, it is saving it as pixels some times nothing.

html For example:

<div id='firstDiv'></div>
 <div id='secondDiv'></div>

css code

#firstDiv{
    width:50%;
    height:50%;
}
#secondDiv{
   width:20%;
   height:50%;
}

Jquery code

$('div').each(function (){
   console.log($(this)[0].style.height);
}

how can i get it as %?

like image 528
Vikram Jakkampudi Avatar asked Nov 07 '25 11:11

Vikram Jakkampudi


2 Answers

To get the value in %, you can divide the value with either the top most node [1st parent in dom]

 parseFloat($(this)[0].style.height / $('#idOfFirstParent').height ()) * 100;

, if you want to get the value in reference to the 1st parent in the DOM or by width of the document [this will start with 0,0 of your screen].

 (parseFloat($(this)[0].style.height/ $('window').height ()) * 100).toFixed(2);

                         or 

 (parseFloat($(this)[0].style.height / $('document').height ()) * 100).toFixed(2);
like image 166
Janak Avatar answered Nov 10 '25 01:11

Janak


Try this, not direct option in jQuery.

var height = ( 100 * parseFloat($(element).css('height')) / parseFloat($(element).parent().css('height')) ) + '%';
like image 35
Shafi PS Avatar answered Nov 10 '25 00:11

Shafi PS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!