JavaScript Code


jQuery – Toggle between show and hide effects for elements



Toggle between Show and Hide effects using jQuery

Selected some HTML elements in the document, toggle between show and hide effects for the elements using jQuery.

Solution

To toggle between show and hide effects for selected HTML elements using jQuery, call toggle() function on the selected elements.

For example, the syntax to toggle between show and hide for paragraphs in the document is

$("p").toggle();

Programs

1. Toggle between show and hide for all paragraphs in the document.

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script>
      function myAction() {
        $("p").toggle();
      }
    </script>
  </head>
  <body>
    <button onclick="myAction()">Toggle show/hide</button>
    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
  </body>
</html>

2. Toggle between show and hide effects when some of the selected elements are hidden, and rest of the selected items are not hidden

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script>
      function myAction() {
        $("p").toggle();
      }
    </script>
  </head>
  <body>
    <button onclick="myAction()">Toggle show/hide</button>
    <p>This is a paragraph.</p>
    <p hidden>This is another paragraph.</p>
  </body>
</html>


copyright @2023