Home >Web Front-end >JS Tutorial >How to Toggle Div Visibility Dynamically with a Button?

How to Toggle Div Visibility Dynamically with a Button?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 17:33:29612browse

How to Toggle Div Visibility Dynamically with a Button?

Dynamically Toggling Div Visibility with a Button

Want to seamlessly toggle the visibility of a div element with a button click? Here's how to achieve it:

Pure JavaScript:

Consider the following HTML structure:

<code class="html"><div id="newpost"></div></code>

To toggle the visibility using pure JavaScript, you can use:

<code class="js">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';
    }
};</code>

jQuery:

With jQuery's simplicity, you can use:

<code class="js">$("#button").click(function() { 
    $("#newpost").toggle();
});</code>

Both solutions allow you to toggle the visibility of the "newpost" div element when the button with the ID "button" is clicked. The div element switches between "hidden" and "visible" states with each button click.

The above is the detailed content of How to Toggle Div Visibility Dynamically with a Button?. 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