How To Hide And Show Div In Jquery

jQuery is a popular JavaScript library that simplifies various HTML document related operations like traversing, event handling, and animations. One of the common tasks web developers come across is hiding and showing <div> elements based on different user interactions.

In this blog post, we’ll look at how to hide and show <div> elements using jQuery.

Setting up jQuery

First, you need to include the jQuery library in your HTML file. You can download it from the official jQuery website or use a CDN, like the one provided by Google:

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js”></script>

Using the .hide() and .show() Methods

jQuery provides two simple methods to hide and show <div> elements: .hide() and .show().

Let’s say we have a <div> with an ID myDiv:

<div id=”myDiv”>This is a sample div.</div>

To hide this div, you can simply use the .hide() method:

  $("#myDiv").hide();
  

Similarly, to show the div, use the .show() method:

  $("#myDiv").show();
  

Using the .toggle() Method

If you want to toggle the visibility of a <div> element based on its current state (hide if it’s visible, show if it’s hidden), you can use the .toggle() method:

  $("#myDiv").toggle();
  

Example: Hide and Show Div on Button Click

Let’s create a simple example where we have two buttons to hide and show a <div> element:

<button id=”hideButton”>Hide Div</button>
<button id=”showButton”>Show Div</button>
<div id=”myDiv”>This is a sample div.</div>

Now, add the following jQuery code to handle button click events and hide/show the div:

  $(document).ready(function() {
    $("#hideButton").click(function() {
      $("#myDiv").hide();
    });

    $("#showButton").click(function() {
      $("#myDiv").show();
    });
  });
  

That’s it! You now know how to hide and show <div> elements using jQuery. These methods can also be applied to other HTML elements. Happy coding!