Home  >  Article  >  Web Front-end  >  How do I toggle the visibility of a DIV element with a button using JavaScript or jQuery?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 10:44:29834browse

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!

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