Home >Web Front-end >JS Tutorial >How do I toggle the visibility of a DIV element with a button using JavaScript or jQuery?
Toggling Visibility of a DIV with a Button
You have a DIV element with an ID of "newpost" whose visibility you want to toggle using a button.
To achieve this, consider the following approaches:
Pure JavaScript:
Implement a JavaScript function to toggle the DIV's visibility:
<code class="javascript">var button = document.getElementById('button'); // Assumes element with id='button' button.onclick = function() { var div = document.getElementById('newpost'); if (div.style.display !== 'none') { div.style.display = 'none'; } else { div.style.display = 'block'; } };</code>
jQuery:
jQuery offers a concise solution using the toggle() method:
<code class="javascript">$("#button").click(function() { // assumes element with id='button' $("#newpost").toggle(); });</code>
The above is the detailed content of How do I toggle the visibility of a DIV element with a button using JavaScript or jQuery?. For more information, please follow other related articles on the PHP Chinese website!