Question:
I need a script that does just that: take the height of the div
, round it to the nearest multiple of 24 and apply the result to the style="height"
of the div
itself.
It needs to be pure Javascript, no Jquery.
Follows the HTML structure
<div id="minhadiv">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis id vulputate enim. Aenean venenatis magna non nisl elementum, a pellentesque metus semper. Integer porta diam consectetur, pretium odio sit amet, euismod urna. Quisque vel dui nec ligula iaculis malesuada et nec magna. Donec turpis nulla, viverra id sem nec, malesuada dictum leo.
</div>
The div
has a height: auto
, however it needs to be height rounded in multiples of 24 as the content is dynamic.
For example, if the content of the div
made it 40px
high, then the script should make it 48px
high, which is the closest multiple of 24 (24*2 = 48px).
Then it would look like this:
<div id="minhadiv" style="height: 48px">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis id vulputate enim. Aenean venenatis magna non nisl elementum, a pellentesque metus semper. Integer porta diam consectetur, pretium odio sit amet, euismod urna. Quisque vel dui nec ligula iaculis malesuada et nec magna. Donec turpis nulla, viverra id sem nec, malesuada dictum leo.
</div>
Now if the div
was 54px
high, the script would also leave it with 48px
(according to rounding to multiples of 24). In this case, the div
already has the overflow: auto
in the CSS file, since the content will exceed the size defined by the script.
Answer:
You can use these two to get the height of the div
:
var alturaAtual = document.getElementById('teste').clientHeight;
Where
var alturaAtual = document.getElementById('teste').offsetHeight;
the difference between offsetHeight
and clientHeight
is that it returns the height including padding
, border
and scrollbar
. You must analyze which is best for your situation.
I'm not sure what you want but I made a function to change the height in multiples of 24.
HTML CODE
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="teste" style="height: 65px;"></div>
</body>
</html>
SCRIPT [UPDATED]
function mudaAltura(idDiv) {
var alturaAtual = document.getElementById(idDiv).offsetHeight;
if (alturaAtual % 24 !== 0) {
var resultado = parseInt(alturaAtual / 24);
var novaAltura = 24 * (resultado + 1);
document.getElementById('teste').style.height = novaAltura + "px";
}
}
Then you call the function setting the DIV ID as a parameter. E.g.: mudaAltura("minhaid");