How to Toggle HTML Display With JavaScript
Edited by Viral, Maluniu, Zoe Volt, Warp550 and 10 others
Here's a quick JavaScript trick to control display settings. All we do is set the display of an element to none, and then use a JavaScript function to toggle the display when a user clicks something else.
Edit Steps
-
1Wrap the content you want to toggle display with in a container.
<div ID="content" style="display:block;">This is content.</div>
Ad -
2Insert 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>
-
3Use an event handeler to trigger the function.
<button onclick="toggleContent()">Toggle</button>
Ad
Edit Tips
Article Info
Categories: JavaScript
Recent edits by: Chris, General Rommel, Peter Mortensen
In other languages:
Español: Cómo alternar la visualización HTML con JavaScript
Thanks to all authors for creating a page that has been read 59,227 times.