How to Show and Hide Elements with jQuery
To show and hide elements with jQuery, use the show()
and hide()
methods.
The hide() and show() Syntax
Both the hide()
and show()
method accept two arguments. The first is a speed parameter and the second is an on complete function.
$(element).hide(speed,onComplete);
$(element).show(speed,onComplete);
Speed
- creates a swing effect that transitions over a set time. Accepts the values, "slow", "fast" or milliseconds.onComplete
- A function to call once the animation is complete.
Hide an Element
Let's create a button that will hide when clicked.
<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
$(this).hide();
});
Show an Element
Let's create a button that will show a hidden element when clicked.
<div id="bar" style="display: none;">Hello</div>
<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
$('#bar').show();
});
Using a Transition and an on Complete Function
Here is another example of hiding an element but with a transition effect of one second and an on complete function.
<div id="bar">Hello</div>
<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
$('#bar').hide(1000, () => {
alert('complete');
});
});
jquery