I have made 3 divs, one a little bit above the other, each separared by a <br>
. However when my function hides one of them, the <br>
is still there, therefore each div is misplaced when all the others are hidden.
function hide1() {
var x = document.getElementById("myDiv1");
if (x.style.display==="none") {
x.style.display="block";
}
else {
x.style.display="none";
}
}
<div id="myDiv1">div 1</div> <br>
<div id="myDiv2">div 2</div> <br>
<div id="myDiv3">div 3</div>
<button onclick="hide1()">Toggle div 1</button>
I have 2 more functions for the other divs.
I tried putting the <br>
inside the <div>
in hopes of <br>
visibility being none as well, but it just didn’t read it.
6
Answers
You’re not hiding the
<br>
.You’re only hiding the
<div>
.You should give the
<br>
elements ids or a class and then hide them with your js script.for example:
Your problem is that you are only hiding the divs, you need to hide the line breaks as well.
if you change your code to this, it will look fine.
Instead of using
<br>
tags to make gaps between divs, use CSS.Forget
br
in the first place. Breaks should not be used for styling of the layout, they are semantically for adding a line break to content, not page layout.Instead use CSS classes and create a simple class that can be toggled on or off for the hiding/showing.
You need to remove the
<br>
when you first toggle and then you need to add it back when you toggle the second time.As gre_gor noted, it’s better to use css to space your divs (
margin-bottom
).It is generally not a good idea to use inline event handlers.
If you actually need the breaks, here is a a way to do that, using event delegation to handle the button.