Skip to content

Commit 0dde2ae

Browse files
committed
take the button text toggle out of the for loop, and hide the button if no images
1 parent 5f593ce commit 0dde2ae

1 file changed

Lines changed: 20 additions & 10 deletions

File tree

javascripts/toggle-images.js

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,29 +4,39 @@ export default function () {
44
const toggleImagesBtn = document.getElementById('js-toggle-images')
55
if (!toggleImagesBtn) return
66

7+
const images = document.querySelectorAll('img')
8+
9+
// If there are no images on the page, hide the button entirely and return.
10+
if (!images.length) {
11+
toggleImagesBtn.style.display = 'none'
12+
return
13+
}
14+
715
const hideText = document.getElementById('js-hide-text')
816
const showText = document.getElementById('js-show-text')
917

1018
// For localization friendliness, the button HTML includes both show and hide text.
1119
// The button should say "Hide" by default, so we suppress the "Show" text here.
1220
showText.style.display = 'none'
1321

14-
const images = document.querySelectorAll('img')
15-
1622
toggleImagesBtn.addEventListener('click', (e) => {
23+
// Check first image to see if images are currently hidden; if so, and there is a click to show them...
24+
if (images[0].style.display === 'none') {
25+
// Button should say "Hide"
26+
showText.style.display = 'none'
27+
hideText.style.display = 'inline'
28+
} else {
29+
// Button should say "Show"
30+
showText.style.display = 'inline'
31+
hideText.style.display = 'none'
32+
}
33+
34+
// Toggle the images on click.
1735
for (const img of images) {
1836
if (img.style.display === 'none') {
19-
// Show images
2037
img.style.display = 'block'
21-
// Say "Hide"
22-
showText.style.display = 'none'
23-
hideText.style.display = 'inline'
2438
} else {
25-
// Hide images
2639
img.style.display = 'none'
27-
// Say "Show"
28-
showText.style.display = 'inline'
29-
hideText.style.display = 'none'
3040
}
3141
}
3242

0 commit comments

Comments
 (0)