jquery toggle visibility

jQuery Toggle Visibility

If you want to toggle the visibility of an HTML element using jQuery, there are a few ways to accomplish this. The easiest way is to use the .toggle() function.

Using .toggle()

The .toggle() function toggles the display property of elements. If an element is hidden with display: none, .toggle() will display the element. If an element is visible with display: block, .toggle() will hide the element.


$('button').click(function(){
  $('p').toggle();
});
  • $('button'): selects the button element
  • click(function(){}): attaches an event listener for when the button is clicked
  • $('p'): selects the paragraph element(s) to toggle
  • .toggle(): toggles the visibility of the paragraph element(s)

Using .show() and .hide()

You can also use the .show() and .hide() functions to show or hide elements respectively.


$('button').click(function(){
  $('p').toggle();
});
  • $('button'): selects the button element
  • click(function(){}): attaches an event listener for when the button is clicked
  • $('p'): selects the paragraph element(s) to toggle
  • .toggle(): toggles the visibility of the paragraph element(s)

Using .show() and .hide() gives you more control over the display property of elements. You can specify the display property to use when showing or hiding the element.


$('button').click(function(){
  $('p').toggle("slow");
});
  • $('button'): selects the button element
  • click(function(){}): attaches an event listener for when the button is clicked
  • $('p'): selects the paragraph element(s) to toggle
  • .toggle("slow"): toggles the visibility of the paragraph element(s) with a slow animation

In this example, the .toggle() function will show the element with a slow animation when it is hidden, and hide the element with a slow animation when it is visible.

Using .show() and .hide() also allows you to specify a callback function to execute when the animation is complete.


$('button').click(function(){
  $('p').toggle("slow", function(){
    alert("Animation complete.");
  });
});
  • $('button'): selects the button element
  • click(function(){}): attaches an event listener for when the button is clicked
  • $('p'): selects the paragraph element(s) to toggle
  • .toggle("slow", function(){}): toggles the visibility of the paragraph element(s) with a slow animation, and executes the callback function when the animation is complete
  • alert("Animation complete.");: the callback function to execute when the animation is complete

In this example, the .toggle() function will show the element with a slow animation when it is hidden, and hide the element with a slow animation when it is visible. When the animation is complete, an alert box will appear.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe