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 in pure Javascript, no Jquery.
Follow 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
, but it needs to have the height rounded to multiples of 24 since 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 nearest multiple of 24 (24*2 = 48px).
Then it would be 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
were to be 54px
high, the script would also make it 48px
(as rounded 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 that the script defined.
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 the 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 by setting the DIV ID as a parameter. Ex.: mudaAltura("minhaid");