I want to do a very simple expand/collapse using JavaScript where when I click “Title”, it shows “Text” (which is hidden when the page first loads). Furthermore, when I click on the “Title” again, I want “Text” to get hidden again.
<div>
<h1>Title</h1>
<p>Text</p>
</div>
I’ve never used jQuery or JavaScript before so it would be great if you can explain just a little bit about how this toggle code works. Thanks.
Well this should do it:
So now let me explain the code.
The first line is accepting a function that will run when the document has finished loading. It is equivalent to:
The code in the middle says, for every
h1element, when it gets clicked, execute a function that finds thepelement next to it and toggle its visibility. Thethisin the first selector refers to the actual<h1>DOM element. I did it this way so if you had a structure like the following, the toggling would only affect the content next to the paragraphs.Cheers!