Home > Web Front-end > CSS Tutorial > How Can I Control Div Visibility with a Button Using JavaScript or jQuery?

How Can I Control Div Visibility with a Button Using JavaScript or jQuery?

Barbara Streisand
Release: 2024-12-21 10:59:09
Original
293 people have browsed it

How Can I Control Div Visibility with a Button Using JavaScript or jQuery?

How to Manipulate Div Visibility Using a Button

You can control the visibility of a div element through a button using various approaches. Here is how it's done:

Pure JavaScript:

This method utilizes the display property of CSS:

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';
    }
};
Copy after login

jQuery:

jQuery offers a more concise approach:

$("#button").click(function() {
    $("#newpost").toggle();
});
Copy after login

Explanation:

The JavaScript method directly toggles the display property of the div between 'none' (hidden) and 'block' (visible). The jQuery method uses the toggle() function, which conveniently handles hiding and showing operations.

The above is the detailed content of How Can I Control Div Visibility 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