Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting height of a div in centimeter using jquery?

I'm having a div , in which I am adding data dynamically, I want to get the height of the particular div in centimeter. Because I need to control the amount of data that can be displayed in that div based on the height.

like image 741
Rosh Avatar asked May 29 '12 07:05

Rosh


People also ask

How can get current height of div in jQuery?

innerHeight() - Returns the height of an element (includes padding) outerWidth() - Returns the width of an element (includes padding and border) outerHeight() - Returns the height of an element (includes padding and border)

How do you measure the height of a div?

Method 1: Using the offsetHeight property: The offsetHeight property of an element is a read-only property and used to return the height of an element in pixels. It includes any borders or padding of the element. This property can be used to find the height of the <div> element.

What is offsetHeight in jQuery?

offsetHeight read-only property returns the height of an element, including vertical padding and borders, as an integer. Typically, offsetHeight is a measurement in pixels of the element's CSS height, including any borders, padding, and horizontal scrollbars (if rendered).

How do I set dynamic height in jQuery?

Answer: Use the JavaScript height() method You can set the height of a <div> box dynamically using the jQuery height() method.


2 Answers

1px = 0.02645833 cm;

or

1 cm = 37.795276px;

See these links:

How to access screen display’s DPI settings via javascript?

How to detect the screen DPI using JavaScript

Pixel to Centimeter?

like image 165
thecodeparadox Avatar answered Sep 18 '22 20:09

thecodeparadox


Here is a little javascript function to convert CSS pixels to centimeters:

function px2cm(px) {
  var d = $("<div/>").css({ position: 'absolute', top : '-1000cm', left : '-1000cm', height : '1000cm', width : '1000cm' }).appendTo('body');
  var px_per_cm = d.height() / 1000;
  d.remove();
  return px / px_per_cm;
}

It inserts a 1000cm x 1000cm empty <div> into the page and then read its height in CSS pixels. By not using magic values (as 1px = 0.02645833 cm suggested above, which only work if your screen DPI is 96) it ensures that the current screen DPI is taken into account.

As the DPI of a screen can never change, you should cache the px_per_cm to avoid any performance hit any time you call this function

like image 33
Jonathan Pasquier Avatar answered Sep 16 '22 20:09

Jonathan Pasquier