Home >Web Front-end >CSS Tutorial >How to Toggle Element Visibility with JavaScript and jQuery?

How to Toggle Element Visibility with JavaScript and jQuery?

Susan Sarandon
Susan SarandonOriginal
2024-12-17 21:07:11441browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn