jQuery hide element while preserving its space in page layout

JqueryHtml

Jquery Problem Overview


Is there a way in jQuery where I can hide an element, but not change the DOM when it's hidden? I'm hiding a certain element but when it's hidden, the elements below it move up. I don't want that to happen. I want the space to stay the same, but the element to be shown/hidden at will.

Can I do this?

Jquery Solutions


Solution 1 - Jquery

Instead of hide(), use:

css('visibility','hidden')

hide() sets the display style to none, which completely removes the element from the document flow and causes it to not take up space.

visibility:hidden keeps the space as it is.

Solution 2 - Jquery

Try setting the visibility to hidden:

$("#id").css("visibility", "hidden");

Solution 3 - Jquery

display: none; will take it out of the content flow so you'll see your other content move into the empty space left behind. (display: block; brings it back into the flow pushing everything out of the way.)

visibility: hidden; will keep it within the content flow taking up space but simply make it invisible. (visibility: visible; will reveal it again.)

You'll want to use visibility if you want your content flow to remain unchanged.

Solution 4 - Jquery

in another answer it is noted that jQuery's fadeTo does not set display:none on completion so might also provide a solution here, rather than using fadeOut for example:

<https://stackoverflow.com/questions/6324957/jquery-hide-a-div-without-disturbing-the-rest-of-the-page>

Solution 5 - Jquery

I previously used opacity: 0 before I saw the visibility: hidden trick.

But in many cases opacity: 0 is problematic, because it lets you interact with the element, even though you can't see it! (As pointed out by DeadPassive.)

Usually that's not what you want. But perhaps occasionally you might?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionslandauView Question on Stackoverflow
Solution 1 - JqueryDr.MolleView Answer on Stackoverflow
Solution 2 - JqueryChad LevyView Answer on Stackoverflow
Solution 3 - JquerySparkyView Answer on Stackoverflow
Solution 4 - JquerylunelsonView Answer on Stackoverflow
Solution 5 - JqueryjoeytwiddleView Answer on Stackoverflow