22 Votes

jQuery: Show and hide elements

Tutorial by Stefan Trost | Last update on 2022-12-29 | Created on 2018-02-28

In this tutorial, I'd like to show you how to make a visible HTML element disappear or how to make an invisible element visible again with the help of JavaScript and jQuery.

In addition, at the end of this tutorial, we look at how you can easily switch back and forth between the visibility and the invisibility of an element using the toggle function.

Show Elements

As a starting point, we have the following invisible DIV container.

<div id="d" style="display:none">Invisible</div>

We would like to display this box now. For making an HTML element visible, jQuery is providing the function .show(), which we now just call with the ID of the DIV box.

$("#d").show();

With a preceding # we can refer to elements via their IDs, with a preceding point . we can address several elements using their class names.

Hide Elements

Similar to the .show() function, jQuery provides the .hide() function for hiding elements.

$("#d").hide();

Otherwise this function works in the same way like .show().

Toggle - Show and hide Element alternately

Sometimes we have the situation that we want to make an element visible or invisible alternately, depending on what state the element is currently in. But we do not need to write an elaborate function with .show() and .hide() because jQuery gives us the function .toggle().

$("#d").toggle();

With .toggle(), the DIV box with the ID "d" will be shown here if it is currently invisible or hidden if it is currently visible.

Influence the Duration of the Fading

If the fading of the elements is too fast or too slow for us, we can pass a time value in milliseconds to the functions .show(), .hide() and .toggle() as a parameter that indicates how much time the function should take.

The default is 400 ms. If it should take twice as long, we can write .show(800), for example. In addition to any numerical value, we can also pass one of the strings "slow" or "fast" to the function that stand for 600 or 200 ms.

ReplyPositiveNegative

About the Author

AvatarYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.