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'));
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'));
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'));
});
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
<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: hiddenkeeps 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.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |