I am trying to create a small script which shows different hidden HTML
items after clicking on a button or link.
Requirements:
- Change button text: Toggle button text from Show more items to Hide items after clicking the button. (And vice versa)
- Multiple collapse: Script must make multiple elements visible
- Nice to have:
display: none
not hardcoded into source code but located in the stylesheet<style>display: none;</style>
- No jQuery or frameworks - Pure minimal lightweight JavaScript
Script base:
I used this Pure Javascript Show/Hide Toggle script as base and modified it.
My modified Code Snippet:
var button = document.querySelector('.toggle-button');
var menu = document.querySelector('.item');
button.addEventListener('click', function (event) {
if (menu.style.display == "") {
menu.style.display = "none";
button.innerHTML = "Show more items";
} else {
menu.style.display = "";
button.innerHTML = "Hide items";
}
}
);
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item hidden-item" style="display: none;">Item 3</div>
<div class="item hidden-item" style="display: none;">Item 4</div>
<div class="item hidden-item" style="display: none;">Item 5</div>
<button class="toggle-button">Show more items</button>
Codepen:
https://codepen.io/anon/pen/ePxeVE
Problem:
My modification does not show the hidden items. I already spent some hours on the issue but I don't get the script working. Any ideas from a JavaScript pro how to show and hide multiple elements when clicking the toggle button?