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

How to Toggle DIV Visibility with a Button Click?

Susan Sarandon
Release: 2024-10-30 06:08:02
Original
280 people have browsed it

How to Toggle DIV Visibility with a Button Click?

How to Toggle the Visibility of a DIV using a Button

This task involves toggling the visibility of a DIV with the click of a button. The following solutions provide comprehensive methods to achieve this functionality:

Pure JavaScript:

In pure JavaScript, the following code can be used:

<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:

If jQuery is available, a more concise solution is:

<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 to Toggle DIV Visibility with a Button Click?. 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!