Home > Web Front-end > JS Tutorial > body text

How do I toggle the visibility of a DIV element with a button using JavaScript or jQuery?

Barbara Streisand
Release: 2024-10-31 10:44:29
Original
845 people have browsed it

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>
Copy after login

jQuery:

jQuery offers a concise solution using the toggle() method:

<code class="javascript">$("#button").click(function() { 
    // assumes element with id='button'
    $("#newpost").toggle();
});</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!