Wednesday, May 5, 2010

Hiding an HTML Element

Most of time people need to change the innerHtml for a container quite often when developing a web page. For example, when you are working on web rich-text editor, and you need to switch the editor from WYSIWYG mode to the source mode. In this case, you might need to hide the preview 'div' and display the edit 'div'. This task is not hard to implement, and also can be implemented in different ways. This blog post will explain several ways to hide the html element.

To make the explaination easier, we need to make some assumptions. Assuming there is a div_A (displaying) and a div_B (not displaying), and if the switch button is clicked, display div_B instead of div_A.

First way is very straight forward: using the style visibility and height attributes. So the code has something like this:
div_B.style.visibility = 'visible';
div_B.style.height = '';
div_A.style.visibility = 'hidden';
div_A.style.height = 0;
div_A.height need to be set to 0, because 'hidden' visibility attribute only hide the element but the space is still there. This method is the way I was using until I found the second way.

Second way is more simple: using the style display attributes. So the code has something like this:
div_A.style.display = 'none';
div_B.style.display = '';
This is much easier, because the display attribute will affect the render list of the page. If it is set to 'none', the page is not going to show this element at all.

Both two methods can hide the html element perfectly, so why not start using the shorter one if you don't know the display attribute before?

No comments:

Post a Comment