There are two ways that I would use to show/hide content:
So what's considered best practice? I can see advantages/disadvantages with both methods.
As an example, I have a site where people can shoot a picture with their webcam. The window in which the webcam resides is showed in a separate window overlapping all other content of the site. When a picture is taken the webcam overlapping is removed again. So I can hide it or insert/remove it.
Style display property is used to hide and show the content of HTML DOM by accessing the DOM element using JavaScript/jQuery. To hide an element, set the style display property to “none”.
The visibility property allows the author to show or hide an element. It is similar to the display property.
You can hide an element in CSS using the CSS properties display: none or visibility: hidden . display: none removes the entire element from the page and mat affect the layout of the page. visibility: hidden hides the element while keeping the space the same.
Visibility: hidden hides the tag, but it still takes up space and affects the page. In contrast, display: none removes the tag and its effects for all intents and purposes, but the tag remains visible in the source code.
There is an in between approach that can take the best of each one of the approaches you mentioned. You mentioned creating and destroying elements using append and remove. It must be made clear that creating an element is a different task from attaching it to the DOM. ie
creating a div
var node = $('<div>node content</div>);
is different than attaching a div:
parent.append(node);
So what you can do is simply assign your elements to variables (ie cache them onto variables) and then attach them and detach them as appropriate. This way you don't have to create the same element everytime you want to use it after having destroyed it (thus incurring a redundant processing cost).
At the same time, you won't have to attach it to the DOM tree unnecessarily then hide it (ie while not using it, thus incurring a UI/UX cost by making the overall experience slower b/c the page is loaded with nodes, some of which aren't used at all by the user).
I think that's the best approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With