Letting the Contents of a Website Disappear


document.getElementById(show).style.display =   "block"; document.getElementById(hide).style.display =   "none"; 

A quite common JavaScript effect on the web that uses CSS is to let elements of a page appear or disappear on request. Some pages implement a waiting screen on a slowly loading page; after the page has been loaded, the waiting screen disappears. Another example is to provide a number of tabsonly one is shown at a time, and switching between them is done using JavaScript, without the need of time-consuming requests to the server.

There are several ways to do this with JavaScript. You can use DOM, and you will find some phrases about letting DOM elements appear and disappear in Chapter 5, "DOM and DHTML." Two alternatives are presented in the phrase.

First, there is the visibility CSS command, which you can set to either visible or hidden to make the associated element appear or disappear. This translates to the JavaScript property visibility. Here is the code:

Setting the Visibility of an Element (visibility.html)

<script language="JavaScript"   type="text/javascript">   function showHide(show, hide) {     document.getElementById(show).style.visibility =       "visible";     document.getElementById(hide).style.visibility =       "hidden";   } </script> <p>&nbsp;<br />&nbsp;</p> <p    style="position: absolute; top: 5px; left: 5px;">   Tab 1 </p> <p  style="position: absolute; top: 5px;      left: 5px; visibility: hidden;">   Tab 2 </p> <input type="button" value="Tab 1"   onclick="showHide('tab1', 'tab2');" /> <input type="button" value="Tab 2"   onclick="showHide('tab2', 'tab1');" /> 

However, as you will see, the absolute positioning leads to some subtle differences across browsers. The best way is to use a block layout and set the display property of the element to either block or none:

Setting the Display Mode of an Element (display.html)

<script language="JavaScript"   type="text/javascript">   function showHide(show, hide) {     document.getElementById(show).style.display =       "block";     document.getElementById(hide).style.display =       "none";   } </script> <p >   Tab 1 </p> <p  style="display: none;">   Tab 2 </p> <input type="button" value="Tab 1"   onclick="showHide('tab1', 'tab2');" /> <input type="button" value="Tab 2"   onclick="showHide('tab2', 'tab1');" /> 

Figure 4.3 shows the result: Clicking on the second button shows the second tab.

Figure 4.3. Clicking on a button shows the associated tab.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net