How to Toggle HTML Display With JavaScript
Wrap the content you want to toggle display with in a container., Insert JavaScript code to change the display., Use an event handler to trigger the function.
Step-by-Step Guide
-
Step 1: Wrap the content you want to toggle display with in a container.
<div ID="content" style="display:block;">This is content.</div> -
Step 2: Insert JavaScript code to change the display.
<script type="text/javascript"> function toggleContent() { // Get the DOM reference var contentId = document.getElementById("content"); // Toggle contentId.style.display == "block" ? contentId.style.display = "none" : contentId.style.display = "block"; } </script>
<button onclick="toggleContent()">Toggle</button> -
Step 3: Use an event handler to trigger the function.
Detailed Guide
<div ID="content" style="display:block;">This is content.</div>
<script type="text/javascript"> function toggleContent() { // Get the DOM reference var contentId = document.getElementById("content"); // Toggle contentId.style.display == "block" ? contentId.style.display = "none" : contentId.style.display = "block"; } </script>
<button onclick="toggleContent()">Toggle</button>
About the Author
Matthew Webb
Writer and educator with a focus on practical cooking knowledge.
Rate This Guide
How helpful was this guide? Click to rate: