ASP.NET RollOver Images

By Fons Sonnemans, 1-1-2002

By Inge Schepers, Fons Sonnemans (Februari 2002)

Download RollOverImageDemo.zip

Introduction

A RollOver image is an image that changes its picture when the mouse moves over it.

Example:      Move your mouse over the image!

There are many ways to implement this. One easy way of doing this is creating a helper class called 'RollOverImageManager'. This helper class does two things: add the 'onMouseOver' and 'onMouseOut' attributes to the image; add a javascript which preloads the 'MouseOver' images.


using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;

namespace RollOverImageDemo
{
    /// <summary>
    /// Utility class for an ASP.NET page that preloads images that
    /// are used for mouseovers.
    ///
    /// Be sure to notice that this code is provided as a technology sample,
    /// 'as is' and no warranties are made by the authors.
    ///
    /// For questions and comments: i.j.m.c.schepers@wxs.nl,
    ///                             Fons.Sonnemans@reflectionit.nl
    ///
    /// </summary>
    public class RollOverImageManager
    {
        private ArrayList mImages;

        public RollOverImageManager()
        {
            mImages=new ArrayList();
        }

        publicvoid AddImage(stringimageURL)
        {
            mImages.Add(imageURL);
        }

        publicvoid InitializeImage(Image control, stringimageURLMouseOver)
        {
            InitializeImage(control,imageURLMouseOver,control.ImageUrl);
        }

        publicvoid InitializeImage(Image control,
                                    stringimageURLMouseOver,
                                    stringimageURLMouseOut)
        {
            AddImage(imageURLMouseOver);

            AddAttribute(control.Attributes,"onMouseOut",imageURLMouseOut);
            AddAttribute(control.Attributes,"onMouseOver",imageURLMouseOver);

        }

        publicvoid InitializeImage(HtmlImage control, stringimageURLMouseOver)
        {
            InitializeImage(control,imageURLMouseOver,control.Src);
            }

        publicvoid InitializeImage(HtmlImage control,
                                    stringimageURLMouseOver,
                                    stringimageURLMouseOut)
        {
            AddImage(imageURLMouseOver);

            AddAttribute(control.Attributes,"onMouseOut",imageURLMouseOut);
            AddAttribute(control.Attributes,"onMouseOver",imageURLMouseOver);

        }

        publicvoid AddAttribute(AttributeCollection a,
                                 stringeventName,
                                 stringimageUrl)
        {
            try
            {
                a.Remove(eventName);
            }
            finally
            {
                a.Add(eventName,"this.src='" +imageUrl+"'");
            }
        }

        /// <summary>
        /// Preload the images
        /// </summary>
        publicvoid LoadImages(Page webPage)
        {
            // Create JavaScript
            StringBuilder buildString=new StringBuilder();
            buildString.Append("\n<SCRIPT LANGUAGE='JavaScript'>\n");
            buildString.Append("<!--\n");
            buildString.Append("var aImages = new Array();\n");
            for(int i =0; i < mImages.Count; i++)
            {
                buildString.Append("aImages[" +
                    i +"] = new Image();\n");
                buildString.Append("aImages[" +
                    i +"].src = '"+
                    mImages[i].ToString()+"';\n");
            }
            buildString.Append("//-->\n");
            buildString.Append("</script>\n");

            // Register Client Script
            if(webPage== null)
            {
                thrownew ArgumentException(
                    "The Page object is invalid.");
            }
            if(webPage.Request.Browser.JavaScript == true)
            {
                webPage.RegisterClientScriptBlock("ImageLoader",
                    buildString.ToString());
            }
        }

    }
}
The InitalizeImage() methods adds the 'onMouseOver' and 'onMouseOut' attributes to the control. The images 'onMouseOver' imageUrl is added to an ArrayList. This ArrayList is used by the LoadImages() method to generate a JavaScript which loads these images. This is done to prevent the extra load of the image the moment you move the mouse over it.

Usage

You use the RollOverImageManager in the Page_Load event of your web page. You create an instance of the class. Initialize the Image controls with the images and call the LoadImage() method.

privatevoid Page_Load(object sender, System.EventArgs e)
{
    // Create the Manager
    RollOverImageManager m =new RollOverImageManager();

    // Intialize the Image Controls
    m.InitializeImage(ImageButton1,"print2.gif");
    m.InitializeImage(Image1,"print2.gif");

    // Load the Images (generate the JavaScript)
    m.LoadImages(this);
}
WebForm1.aspx.cs

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs"
AutoEventWireup="false" Inherits="RollOverImageDemo.WebForm2"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
    <HEAD>
        <metaname="GENERATOR" Content="Microsoft Visual Studio 7.0">
        <metaname="CODE_LANGUAGE" Content="C#">
    </HEAD>
    <body>
        <formid="WebForm1"method="post"runat="server">
            <asp:ImageButton id="ImageButton1"runat="server" ImageUrl="help.gif">
            </asp:ImageButton>
            <asp:Image id="Image1"runat="server" ImageUrl="help.gif">
            </asp:Image>
        </form>
    </body>
</HTML>
WebForm1.aspx

Conclusion

The RollOverImageManager is a simple helper class which lets you implement RollOver images easily. We have also experimented with an other solution. In the solution we subclassed the Image control and added an extra ImageUrlMouseOver property. This property was used to generate the OnMouseOver event. We did not use subclassing because it would lead to a lot of duplicate code unless delegation was used. Using a combination of subclassing and delegation would also take away from the simplicity of the solution, which is why we decided not to use it.

Tags: Web, ASP.NET

Leave a Comment

Leave a Comment
Name
Comment
4 + 3 =

0 Comments

All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.