Home >Web Front-end >CSS Tutorial >How to Toggle Element Visibility with JavaScript and jQuery?
Toggle Element Visibility with a Button
In HTML, sometimes it's necessary to hide or show elements dynamically based on user actions. One common scenario is to toggle the visibility of a div with a button. Here's how to achieve this using pure JavaScript and jQuery.
Pure JavaScript:
This method involves manipulating the element's display property:
var button = document.getElementById('button'); button.onclick = function() { var div = document.getElementById('newpost'); if (div.style.display !== 'none') { div.style.display = 'none'; } else { div.style.display = 'block'; } };
jQuery:
jQuery simplifies the process with the toggle() method:
$("#button").click(function() { // assumes element with>
The above is the detailed content of How to Toggle Element Visibility with JavaScript and jQuery?. For more information, please follow other related articles on the PHP Chinese website!