How To Hide And Show Div Id In Jquery

In this blog post, we’ll explore how to hide and show a div element in your HTML page using jQuery. jQuery is a popular and efficient JavaScript library that simplifies various tasks such as HTML document traversing, event handling, and animation. One of the common use cases for jQuery is to manipulate the visibility of HTML elements, such as a div element, with just a few lines of code.

Step 1: Include jQuery Library

Before you can start using jQuery, you need to include the library in your HTML file. You can either download the library and host it on your server, or you can include it from a Content Delivery Network (CDN) like Google or jQuery’s own CDN. In this example, we will include the jQuery library from Google’s CDN using the following script tag:

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

Step 2: Create the HTML Structure

Next, create the HTML structure for your page, including the div element that you want to hide and show. In this example, we will create a simple div element with an ID attribute, and two buttons for hiding and showing the div:

<div id="myDiv">
  This is the content of the div that we want to hide and show.
</div>

<button id="hideButton">Hide</button>
<button id="showButton">Show</button>
  

Step 3: Write the jQuery Code

Now that you have your HTML structure ready, it’s time to write the jQuery code to hide and show the div element. First, you need to wrap your jQuery code in a $(document).ready() function to ensure that the code is executed when the DOM is fully loaded:

$(document).ready(function () {
  // Your jQuery code here
});
  

Inside the $(document).ready() function, you can use the hide() and show() methods provided by jQuery to manipulate the visibility of the div element. First, attach a click event listener to the “Hide” button:

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

Similarly, attach a click event listener to the “Show” button:

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

Here’s the complete jQuery code:

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

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

Conclusion

In this blog post, we’ve demonstrated how to hide and show a div element in your HTML page using jQuery. By following these steps and leveraging the power of jQuery, you can easily manipulate the visibility of various elements in your web pages. Happy coding!