How to Toggle Show or Hide on Click with jQuery?

Sometimes, we want to toggle show or hide on click with jQuery.

In this article, we’ll look at how to toggle show or hide on click with jQuery.

Toggle Show or Hide on Click with jQuery

To toggle show or hide on click with jQuery, we can use the toggle method in the click handler of the toggle button.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<button>
  toggle
</button>

<div>
  hello world
</div>

to add a toggle button and a div to toggle on and off.

Then we write:

$("button").click(() => {
  $('div').toggle("slide", {
    direction: "right"
  }, 1000);
});

to get the button with $ and add a click event handler to it with click.

In the click handler, we get the div with $.

And we call toggle on it with the effect to apply when toggling and an object to set the direction of the slide.

The 3rd argument is the number of milliseconds to show the transition effect when sliding.

Now when we click toggle, we should see ‘hello world’ being slid right and left when toggling off and on respectively.

Conclusion

To toggle show or hide on click with jQuery, we can use the toggle method in the click handler of the toggle button.