I’m trying to make a jQuery script that will hide all the visible elements on the page,
and then after someone hits a button, make all the elements that were hidden appear again.
I know I can use the .is(':visible') selector on every single divider and store the ones that are visible, then use .hide(); on all of those. Finally, I know I can then use .show(); on them again when someone clicks my button.
But I was wondering if there is a nicer way to do this.
I imagine hiding all elements in one sweep won’t be a big problem (possibly something like $(document).hide() will do it?)
But most importantly how do I store all the elements that were hidden in a nice way so I can restore them again?
Before you hide the elements, apply a class to all of them so you can identify them later:
Alternatively, you don’t really need to use jQuery
eachin this specific case. You can simplify the jQuery function by combining the:visibleselector with the jQuery not selector to exclude the button using thethisvalue:UPDATE:
However, while the above two solutions are great for scenarios where you don’t need user intervention to unhide elements, like in the case of an automated script, the problem with the above 2 examples is that they hide parent elements of the button, which means the button will be hidden, despite it not being explicit. If you require a user to click the button again in order to unhide elements, then the above two solutions are limited.
Thus, the next evolution of this function is to ensure that we exclude the parents using jQuery’s parentsUntil method:
Unhiding all unhideable elements:
Next, when you want to unhide them, simply call:
Finally, if needed, you can clean up after yourself by calling:
DEMO:
See this jsfiddle for a demonstration of this functionality.