Home > Web Front-end > CSS Tutorial > How Can I Show or Hide a DIV Element Using a Button Click?

How Can I Show or Hide a DIV Element Using a Button Click?

Patricia Arquette
Release: 2024-12-14 12:34:14
Original
654 people have browsed it

How Can I Show or Hide a DIV Element Using a Button Click?

How to Toggle Visibility of a DIV with a Button

Question:

How can I show or hide a DIV when a button is clicked?

Answer:

To toggle the visibility of a DIV with a button, you can use either JavaScript or jQuery.

Using Pure JavaScript:

  1. Get a reference to the button element:

    var button = document.getElementById('button');
    Copy after login
  2. Define a function to toggle the visibility:

    button.onclick = function() {
    Copy after login
  3. Get a reference to the DIV element:

    var div = document.getElementById('newpost');
    Copy after login
  4. Check if the DIV is currently shown:

    if (div.style.display !== 'none') {
    Copy after login
  5. Toggle the visibility accordingly:

        div.style.display = 'none'; // Hide
    }
    else {
        div.style.display = 'block'; // Show
    }
    };
    Copy after login

Using jQuery:

  1. Select the button and bind a click event handler:

    $("#button").click(function() {
    Copy after login
  2. Select the DIV and toggle its visibility:

        $("#newpost").toggle();
    });
    Copy after login

The above is the detailed content of How Can I Show or Hide a DIV Element Using a Button Click?. 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