jQuery Show/Hide elements On Button Click

A web page’s ability to display and hide content can increase engagement and improve the user experience. The popular JavaScript package Jquery makes it simpler to complete this operation. In this post, we’ll go through how to use Jquery to show and hide divs in response to a button click.

Let’s start by making a basic HTML page with two divs and a button. The second div is empty, whereas the first div has some material. The second div’s visibility will be toggled using the button. The HTML code for the page is shown below.

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <div id="first_div">
      <p>Some content</p>
    <div id="second_div" style="display:none;">
      <p>Hidden content</p>

We add a script that utilises the.ready() function to run the code after the page is fully loaded after initially included the Jquery library in the HTML page’s head section. The.click() method is used by the function’s code to create a click event for the button element. The div with the id “second_div” may be shown or hidden using the toggle() method. By setting the display property to “none” in the div element’s style attribute, the div is initially hidden.

The toggle() function will display the div if it is hidden and hide it if it is visible when the button is clicked. With only a button click, the Jquery code makes it simple to reveal and conceal the div.

In conclusion, Jquery offers a practical method for displaying and concealing material on a website based on user input. The toggle() method offers a quick and efficient way to complete this operation. You can make dynamic, interactive web pages that improve user experience with just a few lines of code.

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories