I am making a website to serve as a hub for all my creative content. I am doing this for a project and I have been following random tutorials to get to where I am. Currently, I am stumped as a collapsible section I am trying to implement is sort of working. In the sense, that when I click the + changes to a – showing the click is being registered. However, the content does not expand, it remains hidden.
HTML code in question:
<section> <button type="button" class="collapsible"><h5>Click Here to View Entire YouTube Library!</h5></button> <div class="content"> <p>Lorem ipsum...ALLLLLLLLLLLLLLLLLLL</p> </div> <script src="collapsible.js"></script> </section>
JavaScript being used:
var coll = document.getElementsByClassName("collapsible"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block") { content.style.display = "none"; } else { content.style.display = "block"; } }); }
Relates css in case it is required:
.collapsible { background-color: #000; color: #444; cursor: pointer; padding: 18px; width: 100%; border: none; text-align: left; outline: none; font-size: 15px; } .active, .collapsible:hover { background-color: #272727; } .content { padding: 0 18px; background-color: white; max-height: 0; overflow: hidden; transition: max-height 0.2s ease-out; } .collapsible:after { content: '2795'; /* Unicode character for "plus" sign (+) */ font-size: 13px; color: white; float: right; margin-left: 5px; } .active:after { content: "2796"; /* Unicode character for "minus" sign (-) */ }
Please keep in mind, I am a newbie following tutorials so I won’t have deep understanding of the topic yet. Any help is appreciated. Thank You!
Advertisement
Answer
The problem here is wrong styling manipulation, the reason element doesn’t appear is because of overflow
and not display
, display
is either block
or inline
by default (depends on the element). Edit your Javascript code like below:
if (content.style.overflow === "visible") { content.style.overflow = "hidden"; } else { content.style.overflow = "visible"; }
You have explicitly set overflow: hidden
, so that’s why changing the display doesn’t work.