ASP.NET RollOver Images

By Fons Sonnemans, posted on
2779 Views

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;
		
		/// <summary>
		/// Constructor
		/// </summary>
		public RollOverImageManager()
		{
			mImages = new ArrayList();
		}

		/// <summary>
		/// Add a image to the Pre-loadlist
		/// </summary>
		/// <param name="imageURL"></param>
		public void AddImage(string imageURL)
		{
			mImages.Add(imageURL);
		}

		/// <summary>
		/// Initialize the Image (and ImageButton) control
		/// </summary>
		/// <param name="control"></param>
		/// <param name="imageURLMouseOver"></param>
		public void InitializeImage(Image control, string imageURLMouseOver)
		{
			InitializeImage(control, imageURLMouseOver, control.ImageUrl);
		}

		/// <summary>
		/// Initialize the Image (and ImageButton) control
		/// </summary>
		/// <param name="control"></param>
		/// <param name="imageURLMouseOver"></param>
		/// <param name="imageURLMouseOut"></param>
		public void InitializeImage(Image control, 
			                        string imageURLMouseOver, 
			                        string imageURLMouseOut)
		{
			AddImage(imageURLMouseOver);
			
			AddAttribute(control.Attributes, "onMouseOut", imageURLMouseOut);
			AddAttribute(control.Attributes, "onMouseOver", imageURLMouseOver);
			
		}

		/// <summary>
		/// Initialize the HtmlImage (and ImageButton) control
		/// </summary>
		/// <param name="control"></param>
		/// <param name="imageURLMouseOver"></param>
		public void InitializeImage(HtmlImage control, string imageURLMouseOver)
		{
			InitializeImage(control, imageURLMouseOver, control.Src);
		}

		/// <summary>
		/// Initialize the HtmlImage (and ImageButton) control
		/// </summary>
		/// <param name="control"></param>
		/// <param name="imageURLMouseOver"></param>
		/// <param name="imageURLMouseOut"></param>
		public void InitializeImage(HtmlImage control, 
			                        string imageURLMouseOver, 
			                        string imageURLMouseOut)
		{
			AddImage(imageURLMouseOver);
			
			AddAttribute(control.Attributes, "onMouseOut", imageURLMouseOut);
			AddAttribute(control.Attributes, "onMouseOver", imageURLMouseOver);
			
		}

		/// <summary>
		/// Add the 'this.src' event-attribute to the collection
		/// </summary>
		/// <param name="a">collection</param>
		/// <param name="eventName">Eventname</param>
		/// <param name="imageUrl">ImageUrl</param>
		public void AddAttribute(AttributeCollection a, 
			                     string eventName, 
			                     string imageUrl)
		{
			try 
			{ 
				a.Remove(eventName); 
			} 
			finally 
			{ 
				a.Add(eventName, "this.src='" + imageUrl + "'"); 
			} 
		}

		/// <summary> 
		/// Preload the images
		/// </summary> 
		public void 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)
			{
				throw new 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.

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

	// Intialize the Image Controls
	m.InitializeImage(ImageButton1, "print.gif");
	m.InitializeImage(IMG1, "print.gif");

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

WebForm1.aspx.cs

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="RollOverImageDemo.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
	<HEAD>
		<title>WebForm1</title>
		<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
		<meta name="CODE_LANGUAGE" Content="C#">
		<meta name="vs_defaultClientScript" content="JavaScript">
		<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
	</HEAD>
	<body MS_POSITIONING="GridLayout">
		<form id="Form1" method="post" runat="server">
			<IMG id="IMG1" style="Z-INDEX: 101; LEFT: 131px; POSITION: absolute; TOP: 55px" alt="" src="help.gif" runat="server">
			<asp:ImageButton id="ImageButton1" style="Z-INDEX: 102; LEFT: 129px; POSITION: absolute; TOP: 100px" runat="server" ImageUrl="help.gif"></asp:ImageButton>
		</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.

Download

Tags

Web ASP.NET

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.

Leave a comment

Blog comments

0 responses