Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating/destroying HTML elements versus hiding them until needed, which is better?

Tags:

html

jquery

css

There are two ways that I would use to show/hide content:

  1. Create/destroy elements when needed/not needed by using jQuery.append() and jQuery.remove().
  2. 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.

like image 545
xrDDDD Avatar asked Feb 20 '13 13:02

xrDDDD


People also ask

Can you hide HTML elements?

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”.

Which function is used to hide an HTML element?

The visibility property allows the author to show or hide an element. It is similar to the display property.

How do you hide element so it will still takes up the same space as before?

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.

Which style rule should be used to hide an element but still take up empty space on the page?

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.


1 Answers

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.

like image 100
abbood Avatar answered Sep 27 '22 20:09

abbood