Javascript show hide div onclick toggle with example

Javascript show hide div onclick toggle with example

Javascript toggle method simply toggles the visibility of elements. The matched elements will be revealed or hidden immediately, with no animation, by changing the CSS display property.

Simply if the element is initially displayed, it will be hidden; if hidden, it will be shown.

$( ".<elementId>" ).toggle();

Let's take a example:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Toggle Demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<button>Toggle</button>
<p>Hello</p>
<p style="display: none">Legend Blogs User</p>
 
<script>
$( "button" ).click(function() {
  $( "p" ).toggle();
});
</script>
 
</body>
</html>

Animation Speed:

In the another method animates all paragraphs to be shown if they are hidden and hidden if they are visible, completing the animation within 600 milliseconds.

<script>
$( "button" ).click(function() {
  $( "p" ).toggle( "slow" );
});
</script>

After animation complete:

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence.

Loading...

If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole element.

$( "#clickme" ).click(function() {
  $( "p" ).toggle( "slow", function() {
    // Animation complete.
  });
});

Related posts

Write a comment