jQuery Effects: hide, show and toggle

jQuery can show and hide elements with simple methods. You can do it at once or with an animation.

hide() and show()

<p id="text">Hello, this text can be hidden.</p>
$('#text').hide();
console.log($('#text').css('display'));
$('#text').show();
console.log($('#text').css('display'));
Console output

none
block

hide() sets display: none, and show() puts back the normal display.

toggle()

toggle() shows a hidden element and hides a visible one. It is useful for a button which opens and closes something.

<button id="btn">Toggle</button>
<div id="panel">Panel content</div>
$('#btn').on('click', function () {
  $('#panel').toggle();
});

$('#btn').click();
console.log($('#panel').css('display'));
$('#btn').click();
console.log($('#panel').css('display'));
Console output

none
block

Speed and callback

You can give a speed to make it an animation. Use the words 'slow' (600 ms) and 'fast' (200 ms), or the number of milliseconds. The last argument can be a callback, which runs after the effect is complete.

$('#panel').hide(1000);
$('#panel').show('slow');
$('#panel').toggle(400, function () {
  console.log('Effect finished');
});

In our test environment the animations are switched off with $.fx.off = true so the result is instant. The callback example:

<div id="panel">Panel</div>
$('#panel').hide(400, function () {
  console.log('Effect finished, display = ' + $(this).css('display'));
});
Console output

Effect finished, display = none

Show and hide by a condition

<div id="a">A</div>
<div id="b">B</div>
$('#a').toggle(true);    // true = show
$('#b').toggle(false);   // false = hide
HTML after the code runs

<div id="a">A</div>
<div id="b" style="display: none;">B</div>

Hidden elements and visibility

  • hide() removes the element from the layout (display none). The space is free.
  • The CSS visibility: hidden keeps the space. You can set it with .css('visibility', 'hidden').
  • Hidden elements are still in the DOM, so you can get and change their content.

For accessibility

When you hide content, make sure that screen readers and the keyboard users can still use the page. For menus and accordions, also change the aria-expanded attribute.

Note: For many cases, the CSS classes with transitions are smoother and faster than jQuery animations. But the jQuery effects are easy and work everywhere. Next: Fade and Slide Effects.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.