To toggle showing and hiding a div when clicking a button with jQuery, we can use the jQuery toggle
method to toggle a div on and off.
For instance, if we have the following HTML:
<input type='button' id='hideshow' value='hide/show'>
<div id='content'>Hello World</div>
Then we toggle to show and hide a div when we click on the input button by writing:
$(document).ready(() => {
$('#hideshow').on('click', (event) => {
$('#content').toggle('show');
});
});
We call $(‘#hideshow’).on
with 'click'
to add a click event handler for the button.
Then in the event handler, we call toggle
with 'show'
to toggle the div on and off.