How can I show and hide div on mouse click using jQuery?

To show and hide div on mouse click using jQuery, use the toggle() method. On mouse click, the div is visible and on again clicking the div, it hides.

The toggle() method is a convenient jQuery function that automatically switches between showing and hiding elements. When an element is visible, toggle() will hide it, and when it's hidden, toggle() will show it.

Example

Here's a complete example that demonstrates how to show and hide a div on mouse click −

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $('#show').click(function() {
                $('.menu').toggle("slide");
            });
        });
    </script>
    <style>
        #show {
            background-color: #4CAF50;
            color: white;
            padding: 10px 15px;
            cursor: pointer;
            display: inline-block;
            margin-bottom: 10px;
        }
        .menu {
            border: 1px solid #ccc;
            padding: 10px;
            background-color: #f9f9f9;
        }
    </style>
</head>
<body>
    <div id="show">Click to Show/Hide div</div>
    <div class="menu" style="display: none;">
        <ol>
            <li>India</li>
            <li>US</li>
            <li>UK</li>
            <li>Australia</li>
        </ol>
    </div>
</body>
</html>

In this example −

  • The $('#show').click() function attaches a click event handler to the element with ID "show"
  • The $('.menu').toggle("slide") method toggles the visibility of the element with class "menu" using a slide animation
  • The div with class "menu" is initially hidden with style="display: none;"
  • Each click on the button will alternately show and hide the menu div with a smooth sliding effect

Conclusion

Using jQuery's toggle() method provides an easy and effective way to show and hide div elements on mouse click, with optional animation effects like "slide" for better user experience.

Updated on: 2026-03-13T19:40:35+05:30

20K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements