Some old school HTML and JavaScript goodies

Introduction

 
Most of the articles here are focusing on the C# code running on the server, but that's, of course, natural, the site is called C# corner! But hey, we shouldn't forget what we can do with some old school HTML, JavaScript, and CSS. Here comes two, hopefully, useful tip celebrating the client-side.
 
Sometimes you're able to achieve pretty neat things with just some simple HTML and JavaScript. It could actually spice up that old web page quite rapidly! Please, feel free to download the solution file and change it to suit your needs. First, we look at a simple div acting as a modal dialog and then we create a simple JavaScript slideshow.  
 

Disabling the background

 
modal_div.jpg
 
A popular thing to do in some web pages is to fade the background out of focus when displaying some small piece of information to the user. It could be a picture, an informative text or a small form with a submit button asking you for an e-mail address or so.  It's a user-friendly way that really sets focus on what you want to display and it can be made quite easy.
 
Actually, without the CCS styles, I've added to this example, you could do it with three HTML div's, two lines of JavaScript code, one link, some CSS and a small transparent 1x1 image.
 
Here is a snapshot of the HTML markup basics.
  1. <div id="overlay">  
  2.    <div class="info_div">  
  3.      <table width="100%">  
  4.       <tr>  
  5.        <td align="right">  
  6.        <img src="x.gif" onclick="display_overlay(null);" />  
  7.        </td>  
  8.       </tr>  
  9.      </table>  
  10.      <div class="inner_div">Here you can place whatever you want.</div>  
  11.    </div>     
  12. </div> 
     
The div named overlay is the div making the background appear to be "disabled". This by having the height and the width properties set to 100% and the background image set to the small 1x1 png image with 50% transparency. This creates a div that covers the whole browser window and the background image of it makes the page look as it was disabled. These attributes are set in the CCS code as follows.
  1. #overlay  
  2. {  
  3.    visibilityhidden;  
  4.    positionfixed;  
  5.    left: 0px;  
  6.    top: 0px;  
  7.    width:100%;  
  8.    height:100%;  
  9.    background-image:url('overlay.png');  
  10.    z-index:1000;  
  11.  
We set the visibility to hidden by default so that the div doesn't show when loading the page from the start and we set the position to fix. The height and width are set to 100%, the background image to our transparent png image and the z-index to 1000 which places the div in the top most position on the page.
 
The div named info_div is the one that acts like a dialog and inside that div you could put whatever you like, the CSS for that div looks like follows.
  1. .info_div   
  2. {  
  3.     padding:5px;  
  4.     margin:0px;  
  5.     background#ffffff;  
  6.     bordersolid 2px #333333;  
  7.     positionabsolute;  
  8.     width350px;  
  9.     left: 250px;  
  10.     top: 50px;  
  11.  
The only thing we need now is a function that displays the overlay div. We use the getElementById to get a reference to the overlay div and then we just check whether it's visible or not by setting the visibility property of the div object.
  1. <script type="text/javascript">  
  2. function display_overlay(div_element)  
  3. {  
  4.    el = document.getElementById('overlay');  
  5.    el.style.visibility = (el.style.visibility == "visible") ? "hidden" :  
  6.    "visible";  
  7. }  
  8. </script> 
     
Now we can display the div with a simple link.
  1. <a href="javascript:void(0);" onclick="display_overlay('info_div');">Show DIV</a> 
     
You could also add the JavaScript function to a server control by adding the onclick attribute when creating the page.
 
btnServerControl.Attributes.Add("onclick", "display_overlay('info_div'); return false;");
 
The last JavaScript statement, return false, is preventing the page from creating a postback.
 

Enhancements

 
You could have several div's that you want to display like this on the same page, perhaps a logon form, a picture box, etc. It's easy to extend this solution with that feature, just add more div's to the overlay div and name and style them as you wish. Then add JavaScript code to set all those div's visibility property to hidden before calling the visibility property of the div in question.
 

Image slideshow using JavaScript

 
I guess there are one million examples out there. Well, now there are one million and one!
 
Often you have several images you want to display, but a very limited amount of space to do it on. A simple slideshow might do it for you. I've made a really simple but well working example that could be modified quite easily.
 
The basic idea is to enumerate thru a C# collection of images on the server to create a block of JavaScript code handling the slideshow. The script is then added to the page during the page load event. We use an Array object in JavaScript to hold a collection of image links and by using the built-in JavaScript setTimeout function, which take two parameters; the function to call and the delay in milliseconds between the calls, we can make a quite simple loop thru our images and set the src property to the IMG object.
 
The HTML markup for displaying the image and the image name look like follows.
  1. <table>  
  2.   <tr>  
  3.     <td style="height:210px;width:210px;border: solid 1px #999999;" align="center" valign="middle">  
  4.     <asp:Image ID="img" runat="server" ImageUrl="Images/htc_1.jpg" ImageAlign="Middle" />  
  5.     </td>  
  6.   </tr>  
  7.   <tr>  
  8.     <td align="center"><asp:Label runat="server" ID="lblImgHeader"></asp:Label>  
  9.     </td>  
  10.   </tr>  
  11. </table> 
     
We use an Image control to display the image and Label control to display the image name.
 
(The names img and lblImgHeader will be referred to in the JavaScript)
 

Creating the array with images

 
In the example, we loop through all of the images in a folder, but you could supply the images links from a database as well. First, we create the array by selecting all the images in the folder images in the example web application.
  1. string[] images = System.IO.Directory.GetFiles(Server.MapPath("Images"));  
  2. foreach (string image in images)  
  3. {   
  4.    System.IO.FileInfo fi = new FileInfo(image);   
  5.    script.Append("image[" + index.ToString() + "] = 'Images/" + fi.Name + "';");   
  6.    index++;  
  7.  
This is just the creation of the array and as you see, you can easily change it to be created from a database or whatever. You just need to supply a valid path to the images. (Note that this only will work on your PC when you run the solution, the website needs to have a virtual folder called Images to make things happen there)
 
So, the complete listing goes as follows. By checking the length property we can decide whether we should display one image or create and add the script handling the slideshow. We use the HtmlGenericControl class to hold the script we want to create.
  1. if (images.Length != 0)  
  2. {  
  3.    HtmlGenericControl js = new HtmlGenericControl("script");  
  4.    js.Attributes.Add("type""text/javascript");  
  5.    // Create a StringBuilder object for the JavaScript  
  6.    StringBuilder script = new StringBuilder();  
  7.    // Use the setTimeout function to call the function swithImg approx each fourth second.   
  8.    script.Append("setTimeout('switchImg()',4000);");  
  9.    // Create an array to hold the files an assign the total number if pics  
  10.    script.Append("var image = new Array();");  
  11.    script.Append("var total = " + images.Length.ToString());  
  12.    // The number variable is used to keep track of where we are in the loop  
  13.    script.Append("var number = 0");  
  14.    // An int to keep track of the array elements  
  15.    int index = 0;  
  16.    // Loop thru the images in the folder  
  17.    // These links could come from a database, as well...  
  18.    foreach (string image in images)  
  19.    {  
  20.       // As we get them from disk, the image string contains of the  
  21.       // full file directory path. We use the FileInfo class to change it  
  22.       // to map the Images folder in our project.  
  23.       System.IO.FileInfo fi = new FileInfo(image);  
  24.       script.Append("image[" + index.ToString() + "] = 'Images/" + fi.Name + "';");  
  25.       index++;  
  26.    }  
  27.    // Set the first image to be displayed  
  28.    string img_url = "Images/" + new FileInfo(images[0]).Name;  
  29.    img.ImageUrl = img_url;  
  30.    lblImgHeader.Text = img_url;  
  31.    // Create a function displaying each file in the image array  
  32.    script.Append("function switchImg() {");  
  33.    // Get the image object and the label object  
  34.    script.Append("var img = document.getElementById('img');");  
  35.    script.Append("var imgHeader = document.getElementById('lblImgHeader');");  
  36.    // Increase the current index for the image by one  
  37.    script.Append("number = parseInt(number) + 1;");  
  38.    // Check wether thats larger than the total amount of images  
  39.    script.Append("if(number != total)");  
  40.    // If not, display that images url that correspond with the image[index]  
  41.    script.Append("{img.src = image[number];}");  
  42.    // If number == total, we need to start from scratch again. image [0]  
  43.    script.Append("else");  
  44.    script.Append("{number = 0; img.src = image[0];}");  
  45.    // Make sure to display the current image name in the label  
  46.    script.Append("imgHeader.innerHTML = image[number];");  
  47.    // Start the switchImg loop by calling setTimeout  
  48.    script.Append("setTimeout('switchImg()',4000);");  
  49.    script.Append("}");  
  50.    // Set the script text  
  51.    js.InnerText = script.ToString();  
  52.    // Add the control to the header  
  53.    Page.Header.Controls.Add(js);  
  54.  
It might be hard to follow, but if you look at the result of the code above it comes much clearer. 
  1. <script type="text/JavaScript">  
  2.  setTimeout('switchImg()',4000);  
  3.  var image = new Array();  
  4.  var total = 4  
  5.  var number = 0  
  6.  image[0] = 'Images/htc_1.jpg';  
  7.  image[1] = 'Images/htc_2.jpg';  
  8.  image[2] = 'Images/htc_3.jpg';  
  9.  image[3] = 'Images/htc_4.jpg';  
  10.   
  11.  function switchImg()   
  12.  {  
  13.     var img = document.getElementById('img');  
  14.     var imgHeader = document.getElementById('lblImgHeader');  
  15.     number = parseInt(number) + 1;  
  16.     if(number != total)  
  17.     {  
  18.       img.src = image[number];  
  19.    }  
  20.     else  
  21.     {  
  22.       number = 0;  
  23.        img.src = image[0];  
  24.    }  
  25.     imgHeader.innerHTML = image[number];  
  26.    setTimeout('switchImg()',4000);  
  27.  }  
  28. </script> 
     

Let's walk thru the script.

 
First, we have the JavaScript setTimeout function which calls the switching() method after four seconds. Then we have the initialization of the image array holding the image links. Our folder contained four images, so the total variable holds the total number of images. The number variable is hardcoded to 0 as we want to start viewing the image with index 0. (img.src = image[0]) Then is the image links added thru the loop we made.
 
The function itself adds 1 to the number variable and checks whether it is larger or not than the total numbers of images. (Variable total) If not, we display that array index as the image; else we set the number variable to 0 and set that as the current image. At the end of the function we set the image name to the label and then we call the switchImg() function again starting off the loop each fourth second.
 
You could do a combination of the two examples given here by adding an onclick event to the image displaying a larger version of the current image in a div with faded background, but I will not do it for you, you've been given the tools now to create that functionality yourself!


Similar Articles