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
Patricia ArquetteOriginal
2024-12-14 12:34:14710browse

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');
  2. Define a function to toggle the visibility:

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

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

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

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

Using jQuery:

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

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

        $("#newpost").toggle();
    });

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!

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