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.

3 Steps 1 min read Easy

Step-by-Step Guide

  1. Step 1: Wrap the content you want to toggle display with in a container.

    <div ID="content" style="display:block;">This is content.</div>
  2. 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>
  3. 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

M

Matthew Webb

Writer and educator with a focus on practical cooking knowledge.

55 articles
View all articles

Rate This Guide

--
Loading...
5
0
4
0
3
0
2
0
1
0

How helpful was this guide? Click to rate: