Preloading HTML Content with CSS

Get Help With All Aspects of Web Design & Design Software

Moderators: Moderator, Global Moderator

Post Reply
Tami
Administrator
Administrator
Posts: 10892
Joined: Sun Apr 25, 2004 1:05 pm

Preloading HTML Content with CSS

Post by Tami »

Preloading HTML Content with CSS
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]<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]

Now, we define our CSS declarations and HTML, respectively:

[code]    <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>[/code]

Let’s break down the above script to understand how it works. In fact, it’s quite simple.

First, we defined the rotateContent() function, which takes care of transferring the content of each message, stored in the messages array, to a containing <div> 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 <div> as an object and manipulated its content via the innerHTML property, which allows us to display each message alternatively.

Please note the line <div id=\"container\" class=\"regular\"></div>. It has no structural value, but refers to the containing <div> 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]<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>[/code]

As we can see with this approach, since all the messages are stored in variables, adding and updating content is an extremely cumbersome task. This old fashioned solution might be noticeably improved with the assistance of CSS for hiding regular HTML by using the capabilities of the CSS attribute display, as we’ll see in the next section.

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].hidden {
display: none;
}[/code]

Having defined the “hidden” class, with the display property set to “none,” each element which the class is applied to will be initially hidden, creating a set of elements susceptible to being deployed by utilizing a controllable script.

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]<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]

And following, the CSS declarations and HTML markup:

[code]    <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>[/code]

Let’s see in detail how this works:

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 <div> elements present in the document. Once all of the <div> 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 <div> into the containing <div>, 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 <h2> 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 <div> elements, which will be hidden from view initially. Within the divs, we have included several elements, such as <h2> headers and some images. Once again feel free to include anything you want. Finally the containing <div> 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]<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>[/code]

At first glance, we’ve not gone so far as to make something different from the initial example. Take another look. Since we’re fetching content from the “hidden” divs and not directly from javascript variables, the process of adding or updating dynamic content is fairly easy. It’s just a matter of adding or replacing content within the hidden divs, and we’re done. With a simple Content Management System we might quickly add elements to the selected hidden sections, and voila! We have fresh rotating content on our site. Pretty easy, right?

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 <div> 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]<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]

The CSS rules are the following:

[code]<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]

Finally, the HTML markup is listed below:

[code]<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>[/code]

In order to explain the logic behind this code, we’ll see in detail how it works, since this is the subject of the next section.

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]<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>[/code]

Please note the ids attributes assigned to each <a> element. They’re relevant to making our menu work. With the use of javascript, we’ll use these ids to obtain the corresponding <div> menu element either for hiding or displaying it when the user clicks on the link. In a moment, more of this will be explained in the javascript section. Just keep reading.

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]menu=document.getElementById(\'menu\'+this.id);[/code]

The code is executed each time the user clicks on the link. When it is clicked, the corresponding link id is passed to the switchMenu() function, obtaining the id for the <div> menu element, hiding or showing it alternatively. So, for each link clicked, the expression is evaluated in the following manner:

[code]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’;[/code]

As you can see, we’re obtaining the proper <div> menus that match to each link. If the class name of the element is \"hidden\" (menu is hidden), then is set to \"menu\" (menu is displayed), and vice versa, achieving the desired menu effect.

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 <a> 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]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]

Finally, the full code is executed when the page finishes loading:

[code]window.onload=loadGlobalFunctions;[/code]

The complete code for the menu is listed here:

[code]<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>[/code]

The example can be viewed here: [url=\"http://www.devarticles.com/images/stories/Preloading_html_content/example3.htm\"]Example Three[/url]

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]
Image

[color=\"#41211C\"]It takes years to build up trust and only seconds to destroy it

[/color]
Post Reply

Return to “Web Design Principles”