I’m using the display
property on my divs and they are manually toggled on/off by the user when they click a button. I have tried this using the visibility
property and it works, but it leaves a blank space when the div is toggled off, which I don’t want.
Here’s my current code. It does not return any errors; I feel like the logic I tried to implement is just off, but I can’t see it.
function init() {
let current = 1
show(current)
}
function show(n) {
document.getElementById(n).style.setProperty('display', 'block');
let current = n;
for (let i = 1; i < 4; i++) {
if (i != current) {
document.getElementById(i).style.setProperty('display', 'none');
}
}
}
div {
background: red;
padding: 10px;
color: white;
margin: 10px;
display: none
}
html {
background: grey;
}
<body onload="init()">
<!-- no real reason to make a 'main' div, but i plan to when i implement this into my site -->
<div id="main">
<div id="1">div1</div>
<div id="2">div2</div>
<div id="3">div3</div>
<div id="4">div4</div>
</div>
<button onclick="show(1)">show 1</button>
<button onclick="show(2)">show 2</button>
<button onclick="show(3)">show 3</button>
</body>
2
Answers
Your div with id ‘main’ is being hidden with the display none property to the div. Update the css as below
I would suggest to delete button clicks to their parent container.
Also you can avoid looping the divs if they are hidden by default.
Using
<body onload="init()">
is a bad idea because the script runs too late and there’s an unstyled version of the page flicks at the page load.Put you script in the end of the body to avoid that.
Or show the first div at the start by default and then remove that default: