Home > Web Front-end > CSS Tutorial > How to Toggle Element Visibility with JavaScript and jQuery?

How to Toggle Element Visibility with JavaScript and jQuery?

Susan Sarandon
Release: 2024-12-17 21:07:11
Original
445 people have browsed it

How to Toggle Element Visibility with JavaScript and jQuery?

Toggle Element Visibility with a Button

In HTML, sometimes it's necessary to hide or show elements dynamically based on user actions. One common scenario is to toggle the visibility of a div with a button. Here's how to achieve this using pure JavaScript and jQuery.

Pure JavaScript:

This method involves manipulating the element's display property:

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 simplifies the process with the toggle() method:

$("#button").click(function() { 
    // assumes element with>
Copy after login

The above is the detailed content of How to Toggle Element Visibility with JavaScript and 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