Core JavaScript

Collapsible Content

This JavaScript example demonstrates how to create collapsible content so that portions of a page can be hidden or revealed with a simple click.

CollapsibleContent.html

<!DOCTYPE html>
<html>
	<head>
		<title>XoaX.net's Javascript</title>
		<script type="text/javascript" src="CollapsibleContent.js"></script>
		<style>
			.cCollapse {
				background-color: #DFDFDF;
				color: black;
				cursor: pointer;
				border: none;
			}
			.cCollapse:hover {
				background-color: #888;
			}
			.cHiddenNote {
				max-height: 0;
				overflow: hidden;
				transition: max-height 0.2s ease-out;
				background-color: #F0F0F0;
			}
    </style>
	</head>
	<body onload="InitializeCollapsibleNotes()">
		<div><button class="cCollapse">John 1:1-8</button><pre class="cHiddenNote">
In the beginning was the Word, and the Word was with God, and the Word was God.
He was with God in the beginning. Through him all things were made; without him
nothing was made that has been made. In him was life, and that life was the light
of all mankind. The light shines in the darkness, and the darkness has not overcome it.

There was a man sent from God whose name was John. He came as a witness to testify
concerning that light, so that through him all might believe. He himself was not the
light; he came only as a witness to the light.</pre></div>
	</body>
</html>

CollapsibleContent.js

function InitializeCollapsibleNotes() {
	var qaButtons = document.getElementsByClassName("cCollapse");

	for (var i = 0; i < qaButtons.length; i++) {
		qaButtons[i].addEventListener("click", function() {
			this.classList.toggle("active");
			var qCollapsible = this.nextElementSibling;
			if (qCollapsible.style.maxHeight) {
				qCollapsible.style.maxHeight = null;
			} else {
				qCollapsible.style.maxHeight = qCollapsible.scrollHeight + "px";
			}
		});
	}
}
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.