Course Content
AJAX and jQuery Plugins
Learn how to use AJAX and plugins with jQuery to create dynamic and interactive web applications.
0/3
JQuery
About Lesson

Hiding and Showing Elements in jQuery

In this lesson, you will learn how to control the visibility of elements using jQuery. With simple methods, you can hide, show, or toggle the visibility of elements dynamically.

The .hide() method hides the selected element(s) by setting their display property to none.

JavaScript
$("#hide-btn").click(function () {
  $("#content").hide();
});

The .show() method makes a hidden element visible by resetting its display property.

JavaScript
$("#show-btn").click(function () {
  $("#content").show();
});

The .toggle() method switches between hiding and showing the selected element(s).

JavaScript
$("#toggle-btn").click(function () {
  $("#content").toggle();
});

Practical Example:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Hiding and Showing Elements</title>
  <style>
    #content {
      width: 300px;
      height: 150px;
      background-color: lightblue;
      text-align: center;
      line-height: 150px;
      margin: 20px auto;
      border: 1px solid blue;
    }
  </style>
</head>
<body>
  <button id="hide-btn">Hide</button>
  <button id="show-btn">Show</button>
  <button id="toggle-btn">Toggle</button>
  
  <div id="content">This is the content to show or hide.</div>

  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  <script>
    $(document).ready(function () {
      // Hide content
      $("#hide-btn").click(function () {
        $("#content").hide();
      });

      // Show content
      $("#show-btn").click(function () {
        $("#content").show();
      });

      // Toggle content visibility
      $("#toggle-btn").click(function () {
        $("#content").toggle();
      });
    });
  </script>
</body>
</html>

Summary

  • .hide(): Hides an element by setting display: none.
  • .show(): Displays a hidden element.
  • .toggle(): Toggles between hiding and showing the element.