I'm using javascript to show/hide content. I have a link under each content section. When a user clicks the link [show] it shows all content. When the user clicks the link again it hides the content. I would like the link text to change from show to hide, and hide to show on click. Here's an example of what I'm looking to do.
I've managed to solve the show/hide part, but I'm having issues with changing the link text. It only works for Content 1, and not the other parts. I assume this is because querySelectorAll("button")[0]
finds all instances of a.toggle and picks the first occurrence from the array [0]
. I don't know how to apply the javascript to all instances. Thanks.
HTML
<div>
<h1>Title</h1>
<div>Content - Show</div>
<div id="section" style="display:none;">
<div>Content - Hide</div>
</div>
<div><a class="toggle" href="javascript:divHideShow('section');" data-text-swap="Hide">Show</a></div>
</div>
<div>
<h1>Title 2</h1>
<div>Content 2 - Show</div>
<div id="section2" style="display:none;">
<div>Content 2 - Hide</div>
</div>
<div><a class="toggle" href="javascript:divHideShow('section2');" data-text-swap="Hide">Show</a></div>
</div>
<div>
<h1>Title 3</h1>
<div>Content 3 - Show</div>
<div id="section3" style="display:none;">
<div>Content 3 - Hide</div>
</div>
<div><a class="toggle" href="javascript:divHideShow('section3');" data-text-swap="Hide">Show</a></div>
</div>
JS
var toggle = document.querySelectorAll("a.toggle")[0];
toggle.addEventListener('click', function() {
if (toggle.getAttribute("data-text-swap") == toggle.innerHTML) {
toggle.innerHTML = toggle.getAttribute("data-text-original");
} else {
toggle.setAttribute("data-text-original", toggle.innerHTML);
toggle.innerHTML = toggle.getAttribute("data-text-swap");
}
}, false);
function divHideShow(divToHideOrShow) {
var div = document.getElementById(divToHideOrShow);
if (div.style.display == "none") {
div.style.display = "block";
}
else {
div.style.display = "none";
}
}