I tried but it seems to hide and show everything under the button. I would like to hide and show only the images below the button, not the text.
<article>
<h2>Create a new site</h2>
<button id="main button">Hide all screens</button>
<dl id="txt" class="toggle-class">
<dt>Site – Manage Sites - New:</dt>
<dd>
the Site definition Wizard appears, you answer a number of questions
<div class="toggle">
<img class="screenshot" width="238" height="222" src="images/clip_image01.gif" alt="screenshot" />
</div>
</dd>
<dt>“What would you like to call the website?”</dt>
<dd>
enter George's site
<div class="toggle">
<img class="screenshot" width="310" height="307" src="images/clip_image02.gif" alt="screenshot" />
</div>
</dd>
</dl>
</article>
.article {
background-color: white;
border: 1px groove silver;
border-radius: 1em;
margin-left: 230px;
min-width: 700px;
padding: 1em;
width: auto;
}
img.screenshot {
margin-bottom: 20px;
margin-top: 20px;
}
div.toggle {
margin: 10px 0 0 50px;
}
.toggle-class {
display: none;
}
I have tried with " Toggle between hiding and showing an element with JavaScript."
// let txt = document.getElementById("txt");
let toggleButton = document.getElementById("main button");
toggleButton.addEventListener('click', () => {
txt.classList.toggle("toggle-class");
});
CodePudding user response:
Try like following snippet:
const btn = document.querySelector('#main-button')
btn.addEventListener('click', () => {
const images = document.querySelectorAll('.toggle .screenshot')
images.forEach(i => i.classList.toggle('toggle-class'))
images[0].classList.contains('toggle-class') ? btn.innerText = 'Show all screens' : btn.innerText = 'Hide all screens'
})
.article {
background-color: white;
border: 1px groove silver;
border-radius: 1em;
margin-left: 230px;
min-width: 700px;
padding: 1em;
width: auto;
}
img.screenshot {
margin-bottom: 20px;
margin-top: 20px;
}
div.toggle {
margin: 10px 0 0 50px;
}
.toggle-class {
display: none;
}
<article>
<h2>Create a new site</h2>
<button id="main-button">Hide all screens</button>
<dl id="txt" class="">
<dt>Site – Manage Sites - New:</dt>
<dd>
the Site definition Wizard appears, you answer a number of questions
<div class="toggle">
<img class="screenshot" width="238" height="222" src="https://picsum.photos/200" alt="screenshot" />
</div>
</dd>
<dt>“What would you like to call the website?”</dt>
<dd>
enter George's site
<div class="toggle">
<img class="screenshot" width="310" height="307" src="https://picsum.photos/200" alt="screenshot" />
</div>
</dd>
</dl>
</article>