I've been learning Javascript by creating reusable individually collapsible areas (not using jQuery) and I was wondering if someone could review it and let me know if there is anything they would do differently?
Also it would be good if it was usable for screen readers so any usability feedback would be appreciated. If this requires using more CSS and less JS then examples would be helpful.
https://codepen.io/mandrewnz/pen/QgKyjq
HTML
<div class="js-collapsible-region closed">
<h2>Title</h2>
<p>Content goes here</p>
<div>
<button class="js-collapsible-btn">Click to show some text</button>
</div>
<div class="collapsible-area">
<p>Suprise</p>
</div>
</div>
JS
/* adding classlist.js polyfill separately */
var btn = document.getElementsByClassName('js-collapsible-btn');
function findAncestor (el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}
var openHolder = function(e) {
var region = findAncestor(this, 'js-collapsible-region'),
hiddenText = this.childNodes[1];
// set text to reflect collapsible holder status
hiddenText.textContent == "(collapsed)" ? hiddenText.textContent = "(expanded)" : hiddenText.textContent = "(collapsed)";
if (region.classList.contains('closed')) {
region.classList.remove('closed');
region.classList.add('open');
} else {
region.classList.remove('open');
region.classList.add('closed');
}
};
// Create visually hidden text in each link to indicate state
for (var i = 0; i < btn.length; i++) {
var span = document.createElement('span');
var currentBtn = btn[i];
span.classList.add('visuallyhidden');
span.innerHTML = '(collapsed)';
currentBtn.appendChild(span);
// add click event to open holder
btn[i].addEventListener('click', openHolder, false);
}