by Alejandro Gervasio
Website designers often use javascript to expose dynamic content to visitors. Sadly, updating javascript can be painful at best. CSS can help to overcome javascript's limitations -- and the two together open up some lovely possibilities. Alejandro Gervasio explains, with dynamic examples.
When we’re dealing with the common task of fetching some dynamic content to our Web pages to make them more appealing and juicy to visitors, usually we retrieve some database records with dynamic information, properly format them for visual presentation, and finally deliver the visual output to the user’s browser. We congratulate ourselves for that efficient and versatile process; it’s really a nice and straightforward task.
Although most well-structured websites heavily rely on database contents, at times, it’s necessary and even desirable to expose some dynamic content based on client-side techniques. javascript becomes extremely handy when we’re dealing with this scenario, since it is used extensively for displaying content on demand in our Web pages. However, one of the great drawbacks of using javascript to perform that task is that all of the contents have to be stored in variables, within the scripts. This approach makes adding and updating content a very painful and annoying experience.
With the help of CSS, we can improve this situation. CSS helps us to break out of some of the intrinsic javascript limitations, so that common HTML content can be displayed dynamically accordingly to the logic of the master script, without having to deal directly with javascript variables. This way, updating or adding content to our Web page can be a more pleasant process.
Over the next few paragraphs, we’ll be demonstrating how to preload regular HTML content by hiding it from view initially, utilizing the well supported CSS attribute display: none. By implementing this attribute, we can selectively hide different sections of Web pages, and then programmatically bring them back to life, according to the script’s logic. With the core idea in hand, we’ll see some examples employing this CSS technique, proving how powerful it can be. So, let’s move on to find out more.
Let’s say we have a set of messages for displaying in sequence, being commonly implemented as a javascript function, where each message is stored in an array structure and displayed one at a time. A typical solution might be coded in the following manner, first defining the javascript functions:
Code: Select all
<script language="javascript">
// loads global functions
loadGlobalFunctions=function(){
// rotates contents every 5 seconds
rotateContent=function(){
i++;
if(i==message.length){i=0}
container.innerHTML=message[i];
setTimeout('rotateContent()', 5*1000);
}
// defines messages array
var message=new Array();
message[0]='<a href="http://www.google.com">Google takes you where you want!</a>';
message[1]='<a href="http://www.devshed.com">Looking for high quality content? Visit Devshed.com now!</a>';
message[2]='<a href="http://www.devarticles.com">Need for web development articles? Go Devarticles.com!</a>';
var i=0;
var container=document.getElementById('container');
// execute rotateContent function
rotateContent();
}
// execute code once page is loaded
window.onload=loadGlobalFunctions;
</script>Code: Select all
<style type="text/css">
.regular {
font: bold 11px "Verdana", Arial, Helvetica, sans-serif;
color: #000;
}
</style>
<p class="regular">Regular Content</p>
<br />
<div id="container" class="regular"></div>First, we defined the rotateContent() function, which takes care of transferring the content of each message, stored in the messages array, to a containing element that will display them in turn.
We set a time interval of five seconds to show the content sequentially, only for example purposes. Then, we grasped the container as an object and manipulated its content via the innerHTML property, which allows us to display each message alternatively.
Please note the line . It has no structural value, but refers to the containing for displaying HTML content.
Finally, the script is executed once the page is loaded.
The working example can be viewed here: [url="http://www.devarticles.com/images/stories/Preloading_html_content/example1.htm"]Example One[/url]
The complete code for this content rotator is as follows:
Code: Select all
<html>
<head>
<title>CONTENT ROTATOR EXAMPLE</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script language="javascript">
// loads global functions
loadGlobalFunctions=function(){
// rotate contents every 5 seconds
rotateContent=function(){
i++;
if(i==message.length){i=0}
container.innerHTML=message[i];
setTimeout('rotateContent()', 5*1000);
}
// defines messages array
var message=new Array();
message[0]='<a href="http://www.google.com">Google takes you where you want!</a>';
message[1]='<a href="http://www.devshed.com">Looking for high quality content? Visit Devshed.com now!</a>';
message[2]='<a href="http://www.devarticles.com">Need for web development articles? Go Devarticles.com!</a>';
var i=0;
var container=document.getElementById('container');
// execute rotateContent function
rotateContent();
}
// execute code once page is loaded
window.onload=loadGlobalFunctions;
</script>
<style type="text/css">
.regular {
font: bold 11px "Verdana", Arial, Helvetica, sans-serif;
color: #000;
}
</style>
</head>
<body>
<p class="regular">Regular Content</p>
<br />
<div id="container" class="regular"></div>
</body>
</html>As mentioned previously, hiding regular HTML content from being viewed initially, and then presenting it to the user based on a programmatic schema, is a two-step process which can be easily achieved with the use of CSS and javascript respectively. First we select which page’s sections will be hidden from view by applying the display: none property to each of the selected elements, preloading that content in a background process (while the page is loading into the browser). In the second step, we manipulate those elements by the logic of javascript code, to be showed to the end user according to the desired functionality and visual effect.
The CSS code for hiding selected content is basically the following:
Code: Select all
.hidden {
display: none;
}As you may have guessed, building a hidden structure as a transparent process to the visitor, and having the ability to manipulate it as we wish, is an extremely powerful technique that can be exploited to achieve a huge range of effects, with little effort from us.
From dynamic forms, to content rotators, drop-down menus, or image galleries, to name a few, Web designers can use this technique for almost endless creative possibilities. For the scope of this article, we’ll show some detailed examples implementing this approach. The rest of the possible applications will be left as homework for your own future inspiration. So, what are we waiting for? Let’s dive into the first example, which involves rewriting the content rotator previously presented using the new technique.
A wide variety of content rotators are present on websites, which very often offer content on demand. As mentioned above, we’ll create a client–side content version by utilizing the CSS approach and the power of javascript. So, with the preliminaries out of the way, let’s write a little bit of code, presenting a new improved version of the content rotator. Here are the javascript functions:
Code: Select all
<script language="javascript">
// loads global functions
loadGlobalFunctions=function(){
// rotates dynamic content every 2 seconds
rotateContent=function(){
i++;
if(i==hiddenDivs.length){i=0}
container.innerHTML=hiddenDivs[i].innerHTML;
setTimeout('rotateContent()', 2*1000);
}
// gets all <div> elements
divs=document.getElementsByTagName('div');
hiddenDivs=[];
// makes array of <div> elements with class name 'hidden'
for(i=0;i<divs.length;i++) {
if(/\bhidden\b/.test(divs[i].className)){
hiddenDivs[hiddenDivs.length]=divs[i];
}
}
var i=0;
// puts dynamic content into cointaning <div> element
var container=document.getElementById('container');
// executes rotateContent function
rotateContent();
}
// executes code once page is loaded
window.onload=loadGlobalFunctions;
</script>Code: Select all
<style type="text/css">
.hidden {
display: none;
}
h2 {
font: bold 11px "Verdana", Arial, Helvetica, sans-serif;
color: #000;
}
</style>
<div class="hidden"><h2>Frame 1</h2><img src="i1.jpg" alt="" width="120" height="200" /></div>
<div class="hidden"><h2>Frame 2</h2><img src="i2.jpg" alt="" width="120" height="200" /></div>
<div class="hidden"><h2>Frame 3</h2><img src="i3.jpg" alt="" width="120" height="200" /></div>
<div class="hidden"><h2>Frame 4</h2><img src="i4.jpg" alt="" width="120" height="200" /></div>
<h2 class="regular">Regular Content</h2>
<div id="container" class="regular"></div>As usually, we first define our javascript functions. The rotateContent() function behaves similarly to the old fashioned example, but this time there are significant differences. First we iterate over the elements present in the document. Once all of the elements with the “hidden” class name attribute have been stored as an array, the script takes care of putting in turn the content of each hidden into the containing , using the innerHTML property. Then it effectively rotates the content of all the hidden divs.
The rotating process is tackled by a function which changes the contents every two seconds, according to the example. All the code is executed when the page finishes loading.
Next, we have declared our "hidden" class in the CSS, and redefined the header to achieve a styled version. Feel free to include any rule that you might want to use.
In our markup, we’ve defined four hidden elements, which will be hidden from view initially. Within the divs, we have included several elements, such as headers and some images. Once again feel free to include anything you want. Finally the containing is added, with no structural value, but useful for showing dynamic content.
The working example can be viewed here: [url="http://www.devarticles.com/images/stories/Preloading_html_content/example2.htm"]Example Two[/url]
The full code for the content rotator is listed below:
Code: Select all
<html>
<head>
<title>IMPROVED CONTENT ROTATOR EXAMPLE</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script language="javascript">
// loads global functions
loadGlobalFunctions=function(){
// rotates dynamic content every 2 seconds
rotateContent=function(){
i++;
if(i==hiddenDivs.length){i=0}
container.innerHTML=hiddenDivs[i].innerHTML;
setTimeout('rotateContent()', 2*1000);
}
// gets all <div> elements
divs=document.getElementsByTagName('div');
hiddenDivs=[];
// makes array of <div> elements with class name 'hidden'
for(i=0;i<divs.length;i++) {
if(/\bhidden\b/.test(divs[i].className)){
hiddenDivs[hiddenDivs.length]=divs[i];
}
}
var i=0;
// puts dynamic content into cointaning <div> element
var container=document.getElementById('container');
// executes rotateContent function
rotateContent();
}
// executes code once page is loaded
window.onload=loadGlobalFunctions;
</script>
<style type="text/css">
<!--
.hidden {
display: none;
}
h2 {
font: bold 11px "Verdana", Arial, Helvetica, sans-serif;
color: #000;
}
-->
</style>
</head>
<body>
<div class="hidden"><h2>Frame 1</h2><img src="i1.jpg" alt="" width="120" height="200" /></div>
<div class="hidden"><h2>Frame 2</h2><img src="i2.jpg" alt="" width="120" height="200" /></div>
<div class="hidden"><h2>Frame 3</h2><img src="i3.jpg" alt="" width="120" height="200" /></div>
<div class="hidden"><h2>Frame 4</h2><img src="i4.jpg" alt="" width="120" height="200" /></div>
<h2 class="regular">Regular Content</h2>
<div id="container" class="regular"></div>
</body>
</html>
</html>Next, we’re going to employ the same technique to create a simple drop-down menu, with minimal effort.
So far, we‘ve shown a couple of examples to clearly demonstrate how powerful and handy this hiding technique can be for generating on demand content. It would be good to expand out those capabilities to build up different applications, exposing the whole gamut of possibilities when using CSS to hide Web page elements. So, let’s start increasing our creativity by creating a simple drop-down menu, which is very suitable for our sample needs.
The basic logic to creating the drop-down menu consists of hiding and displaying selected elements using the CSS display property, accordingly to the occurrence of an event -- generally, when the user clicks on a specific area or passes the mouse over it. Having defined the general concept, all we have to do is create our menu.
As usual, here is the code for our javascript functions:
Code: Select all
<script language="javascript">
// loads global functions
loadGlobalFunctions=function(){
// switches on-off menu display
switchMenu=function(){
menu=document.getElementById('menu'+this.id);
if(menu.className=='hidden'){
menu.className='menu';
}
else{
menu.className='hidden';
}
}
// gets all <a> elements
as=document.getElementsByTagName('a');
navAs=[];
// makes array from <a> elements with class name 'navbar'
for(i=0;i<as.length;i++){
if(/\bnavbar\b/.test(as[i].className)){
navAs[navAs.length]=as[i];
// assigns onclick event handler to navbar <a> elements
navAs[i].onclick=switchMenu;
}
}
}
// executes code once page is loaded
window.onload=loadGlobalFunctions;
</script>Code: Select all
<style type="text/css">
#button0 {
position: absolute;
width: 15%;
top: 10px;
left: 0px;
}
#button1 {
position: absolute;
width: 15%;
top: 10px;
left: 15%;
}
#button2 {
position: absolute;
width: 15%;
top: 10px;
left: 30%;
}
#menu0 {
position: absolute;
width: 14%;
top: 30px;
left: 0px;
}
#menu1 {
position: absolute;
width: 14%;
top: 30px;
left: 15%;
}
#menu2 {
position: absolute;
width: 14%;
top: 30px;
left: 30%;
}
.hidden {
display: none;
}
a.navbar:link,a.navbar:visited {
display: block;
background: #0f0;
font: bold 11px "Verdana", Arial, Helvetica, sans-serif;
color: #000;
padding: 2px;
text-align: center;
text-decoration: none;
border: 1px solid #000;
}
a.navbar:hover {
text-decoration: underline;
}
.menu {
display: block;
background: #ffc;
font: normal 11px "Verdana", Arial, Helvetica, sans-serif;
color: #000;
padding: 4px;
border: 1px solid #000;
}
</style>Code: Select all
<div id="button0"><a href="#" class="navbar" id="0">Company</a></div>
<div id="button1"><a href="#" class="navbar" id="1">Products</a></div>
<div id="button2"><a href="#" class="navbar" id="2">Contact</a></div>
<div class="hidden" id="menu0">
Profile<br />
Staff
</div>
<div class="hidden" id="menu1">
Web Compilers<br />
HTML Editors<br />
PHP Editors<br />
Database Software
</div>
<div class="hidden" id="menu2">
Technical Support<br />
Knowledge Base<br />
Administrative Support
</div>The code seems a little complex, but really isn't at all. For the sake of clarity, let’s carefully examine what it does.
First, we defined three contextual selectors in the CSS, corresponding to the menu buttons that will compose the navigation bar. They are absolute positioned (you can change this to fit your own needs), and widths are set properly to 15 percent. So, our navigation bar consists of “button0,” “button1,” and “button2” respectively.
In the next step, we declared the three menus corresponding to each button, similarly defined as we did before: “menu1,” “menu2,” and “menu3." Again, these menus have widths of 14 percent and are absolute positioned.
Once we have defined the main containers for the menu, we need to declare the proper classes to specify the look of buttons and menus. In fact, they are very simplistic. Declaring the “navbar” and “menu” classes in turn does this. Feel free to modify these setting to your own taste (backgrounds, colors, borders, etc.).
Then, we define our “workhorse” class, named “hidden,” which is used to hide the menu divs from view.
Finally, we’re going to dive into the HTML markup section. As we can see, we define the three containing divs for each button, including the links, properly styled.
Code: Select all
<div id="button0"><a href="#" class="navbar" id="0">Company</a></div>
<div id="button1"><a href="#" class="navbar" id="1">Products</a></div>
<div id="button2"><a href="#" class="navbar" id="2">Contact</a></div>The javascript code usually begins defining our global function, to be executed once the page is loaded.
Next, we declare the switchMenu() function, which takes care of hiding and displaying accordingly the menus for each button. Please, take a look at the following line:
Code: Select all
menu=document.getElementById('menu'+this.id);Code: Select all
menu= document.getElementById('menu0'); // gets the <div> with id=’menu0’;
menu= document.getElementById('menu1'); // gets the <div> with id=’menu1’;
menu= document.getElementById('menu2'); // gets the <div> with id=’menu1’;Of course, there are many ways of doing this using the DOM, and certainly id names are not fully W3C compliant, but for the purposes of the example, this is more than enough. The rest of the code is pretty self-explanatory. The script iterates over all the elements present in the document, building an array with those found with "navbar" as class name attribute, and assigning the onclick event handler to each one of them.
Code: Select all
as=document.getElementsByTagName('a');
navAs=[];
// makes array from <a> elements with class name 'navbar'
for(i=0;i<as.length;i++){
if(/\bnavbar\b/.test(as[i].className)){
navAs[navAs.length]=as[i];
// assigns onclick event handler to navbar <a> elements
navAs[i].onclick=switchMenu;
}
}Code: Select all
window.onload=loadGlobalFunctions;Code: Select all
<html>
<head>
<title>DROP DOWN MENU EXAMPLE</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script language="javascript">
// loads global functions
loadGlobalFunctions=function(){
// switches on-off menu display
switchMenu=function(){
menu=document.getElementById('menu'+this.id);
if(menu.className=='hidden'){
menu.className='menu';
}
else{
menu.className='hidden';
}
}
// gets all <a> elements
as=document.getElementsByTagName('a');
navAs=[];
// makes array from <a> elements with class name 'navbar'
for(i=0;i<as.length;i++){
if(/\bnavbar\b/.test(as[i].className)){
navAs[navAs.length]=as[i];
// assigns onclick event handler to navbar <a> elements
navAs[i].onclick=switchMenu;
}
}
}
// executes code once page is loaded
window.onload=loadGlobalFunctions;
</script>
<style type="text/css">
#button0 {
position: absolute;
width: 15%;
top: 10px;
left: 0px;
}
#button1 {
position: absolute;
width: 15%;
top: 10px;
left: 15%;
}
#button2 {
position: absolute;
width: 15%;
top: 10px;
left: 30%;
}
#menu0 {
position: absolute;
width: 14%;
top: 30px;
left: 0px;
}
#menu1 {
position: absolute;
width: 14%;
top: 30px;
left: 15%;
}
#menu2 {
position: absolute;
width: 14%;
top: 30px;
left: 30%;
}
.hidden {
display: none;
}
a.navbar:link,a.navbar:visited {
display: block;
background: #0f0;
font: bold 11px "Verdana", Arial, Helvetica, sans-serif;
color: #000;
padding: 2px;
text-align: center;
text-decoration: none;
border: 1px solid #000;
}
a.navbar:hover {
text-decoration: underline;
}
.menu {
display: block;
background: #ffc;
font: normal 11px "Verdana", Arial, Helvetica, sans-serif;
color: #000;
padding: 4px;
border: 1px solid #000;
}
</style>
</head>
<body>
<div id="button0"><a href="#" class="navbar" id="0">Company</a></div>
<div id="button1"><a href="#" class="navbar" id="1">Products</a></div>
<div id="button2"><a href="#" class="navbar" id="2">Contact</a></div>
<div class="hidden" id="menu0">
Profile<br />
Staff
</div>
<div class="hidden" id="menu1">
Web Compilers<br />
HTML Editors<br />
PHP Editors<br />
Database Software
</div>
<div class="hidden" id="menu2">
Technical Support<br />
Knowledge Base<br />
Administrative Support
</div>
</body>
</html>And that’s all. We now have a functional drop-down menu, which relies on the CSS display property to work seamlessly. Just imagine the possible additions to it, or even better, make your own version by improving the script and becoming a great coder yourself. The challenge is really fun!
Conclusion
Through this article, we have appreciated the power of preloading selected content within Web pages, by hiding it for further programmatic manipulation. As seen in the examples shown here, possibilities are endless to fully exploit this ability, expanding our capabilities even more for adding richness to websites and finding better ways of delivering content to end users. The combination of using the CSS display property and a little javascript rewards you with awesome power.
[url="http://www.devarticles.com/c/a/HTML/Preloading-HTML-Content-with-CSS/"]source: DevArticles[/url]

