Wednesday, February 20, 2008

Dynamically show/hide HTML elements using DIV tags

Using "div" tags and their 'style.visibility' property, its relatively easy to show/hide dynamically created HTML elements. As normal every HTML element needs to have a UNIQUE ID inorder for this functionality to be achieved.

Initially when the HTML document is loaded we call a method 'ofPageInit()' which creates the tag and say a 'textarea' HTML element which has to be shown on clicking a button or link.

The code

mybox = document.createElement('textarea');
mybox.setAttribute('id', editArray[i].id);
mybox.setAttribute('rows','2');
mybox.setAttribute('cols','15');

is used to create dynamically a textarea HTML element. The Id of this textarea is set based on the "TD"'s id. Using setAttribute() we specify that we need 2 rows and 15 columns for the dimensions of this text area.


Next we create dynamic "div" tags

mydiv = document.createElement('div');
mydiv.setAttribute('id', 'div'+editArray[i].id);
mydiv.style.visibility = 'hidden';

and set their initial 'visibility' property to hidden so that it is not displayed on screen when the form is first loaded.

We then create a dynamic anchor tag

myCancellink = document.createElement('a');
myCancellink.onclick = hidebox ;
myCancellink.href = "#";
myCancellink.innerHTML = "cancel";

onclicking the link 'cancel', the method 'hidebox' is called. This method sets the 'parentElement', in this case the "div"tag, 'visibility' property to 'hidden' so that it does not get displayed on screen.

On clicking the 'edit' link, we just change the 'visibility' property to 'visible' so that the corresponding "div" tags content is displayed on screen.

No comments: