How to show and hide div on mouse click in jQuery?

By Saruque Ahamed Mollick

Hi, in this post we are going to learn how to show and hide div on mouse click in jQuery. In this JavaScript tutorial, I will show you an easy example where I will make a div element hidden and unhidden using jQuery.

So what will we need to do to learn this is:



  • Create a div element
  • Add clickable element ( We gonna use button here for example )
  • Create jQuery function to be triggered when the mouse button is clicked on the clickable element.

You may also read,

Add and remove attribute in jQuery

Alert Before Leaving A Web Page Using JavaScript – jQuery

Show and hide div on mouse click in jQuery

In the below easy example, We gonna create a div element and two clickable buttons. When the user will click on those buttons the div element will be shown and hidden.

You need to include jQuery in your file.

You can include it with this:

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

Or you can also save the jQuery file locally then include it with the path.

Take a look at this below example:

<!DOCTYPE html>
<html>
<head>
<title>Your title goes here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="text">Hey there! I am gonna be hidden and shown with below button click</div>
<button id="hide_me">Hide</button>
<button id="show_me">Show</button>
<script>
$(document).ready(function(){
    $("#hide_me").click(function(){
        $("#text").hide();
    });
    $("#show_me").click(function(){
        $("#text").show();
    });
});
</script>

</body>
</html>
<div id="text">Hey there! I am gonna be hidden and shown with below button click</div>

This is the div element, I am gonna make hidden and unhidden.

<button id="hide_me">Hide</button> 
<button id="show_me">Show</button>

These are two buttons I have used to hide and show the above div element of id text

$(document).ready(function(){
    $("#hide_me").click(function(){
        $("#text").hide();
    });
    $("#show_me").click(function(){
        $("#text").show();
    });
});

Here I have defined two jQuery functions for those two buttons.

.hide() and .show() method will hide and show the element.

Also read,

How to Hide HTML Element onclick in jQuery Easily

Show or hide input field based on checkbox using jQuery

Leave a Reply

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