Russell Bateman
last update:
In the HTML <head>er, create the following <div> definitions. You can put any styles you want to apply to the <div> that you want inside it, here we're just making sure the id exists to be referenced in the HTML and recognized by the JavaScript function.
<html>
<head>
<style>
#my-div { width: 100%; }
</style>
</head>
<body>
...
</body>
</html>
In the HTML <body> add the <div> with its identifying id attribute and the contents that you want to hide/unhide:
<div id="my-div">
<p>
This is a paragraph or other content that I wish to collapse/fold/hide
based on toggling a button.
</p>
</div>
Either before or after that paragraph or content, place the button to be clicked:
<button onclick="showDiv()"> Click this button to hide or unhide </button>
Near the bottom of the HTML source (if you like), create a JavaScript function that will do the hiding/unhiding. If you're hiding/unhiding more than one of these <div> ranges, you'll need to make the function's name very specific since you'll need one function per instance (and they all must have different names and different <div> ids, etc.):
<script>
function showDiv()
{
var element = document.getElementById( "my-div" );
if( element.style.display === "none" )
element.style.display = "block";
else
element.style.display = "none"
}
</script>
And here's what the final HTML source might look like:
<html>
<title> Demonstration of hide/unhide </title>
<head>
<style>
#my-div { width: 100%; }
</style>
</head>
<body>
<h1> Demonstration of hide/unhide </h1>
<button onclick="showDiv()"> Click this button to hide or unhide </button>
<div id="my-div">
<p>
This is a paragraph or other content that I wish to collapse/fold/hide
based on toggling a button.
</p>
</div>
<script>
function showDiv()
{
var element = document.getElementById( "my-div" );
if( element.style.display === "none" )
element.style.display = "block";
else
element.style.display = "none"
}
</script>
</body>
</html>
It would look like this. (Because I have this at the end of the page, it affects length and its operation may appear a little squirrely.
This is a paragraph or other content that I wish to collapse/fold/hide based on toggling a button.