There are two ways that I would use to show/hide content:
- Create/destroy elements when needed/not needed by using jQuery.append() and jQuery.remove().
- Have everything already in the html but hide/disable those elements when appropriate.
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.
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
is different than attaching a div:
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.