Home  >  Article  >  Web Front-end  >  How to Toggle Div Visibility with a Button?

How to Toggle Div Visibility with a Button?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 09:05:02296browse

How to Toggle Div Visibility with a Button?

Toggle Div Visibility with Button

This article addresses the common task of toggling the visibility of a div element using a button.

Problem:

You have a div that you want to hide or show depending on the user's interaction with a button.

Solution:

Pure JavaScript:

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

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

By utilizing these scripts, you can control the visibility of your div element dynamically, allowing users to hide or reveal its content as needed.

The above is the detailed content of How to Toggle Div Visibility 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