When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles [1.x] [2.0]
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
Headlines from ASPWire.com
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article
Jobs
















internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this Page!

Windows Systems Administrator
Jupitermedia
US-CT-Darien

Justtechjobs.com Post A Job | Post A Resume

Published: Wednesday, September 17, 2003

Creating a RollOver Button Server Control
By Scott Mitchell


Introduction
Recently an individual I am beginning to train in ASP.NET emailed me and asked if there was an easy way to provide roll-over buttons in an ASP.NET Web page. Roll-over buttons, which you'll find on a number of Web sites, are buttons that display a default image whenever the mouse is not hovered above the button, and a different, "selected" image when the mouse is hovered above the button. An example can be seen below (clicking this button will just cause the Web Form it is placed within to postback, refreshing the page...):

- continued -

Note that, by default, the button has a dark red background. If, however, you move the mouse over the button, it changes its background color to a bright red. In this article we'll look at the client-side code needed to create a roll-over button, and then we'll turn our attention to building a roll-over button server control.

The Basics of Creating a Roll-Over Button
The first step in creating a roll-over button is to create two graphic files: one for the roll-over button's default state, and one for when the button is hovered over with the mouse cursor. Being a stellar artist, I opened up Microsoft Paint and spent the next 15 minutes creating these ugly images:

Next, to create the button, you need to create a hyperlink tag (<a>) with the default image as the contents of the hyperlink. Furthermore, it is important to set the name attribute of the <img> tag to some unique value, since we'll need to refer to this later in client-side JavaScript code. For example, I named the default button here home.gif, meaning I would use the following HTML:

<a href="...">
  <img src="home.gif" name="home_img" border="0" />
</a>

Next, we need to write a bit of client-side JavaScript code. Specifically, we need to create two Image objects for each roll-over button. A JavaScript Image object preloads a specified image. This allows us to automatically switch between the default image and the roll-over image without having to have the user download the actual roll-over image when he or she mouses over the button for the first time. The code to accomplish this is fairly straightforward and looks like this:

<script language="JavaScript">
  home_img_out = new Image();
  home_img_out.src = "home.gif";

  home_img_over = new Image();
  home_img_over.src = "home_over.gif";
</script>  

Note that the Image object has a src property by which the image's URL is specified.

Our next task at hand is to write the JavaScript function that will switch a button from one image to another. This function, which we'll name display(), will take in two input parameters. The first specifies the name attribute of the <img> tag whose image we want to change. The second parameter specifies the name of the Image object with which we want to replace the specified <img> tag's current image. The display() function is relatively simple, only taking two lines of code:

<script language="JavaScript">
<!--
  function display(imgName, imgUrl) {
    if (document.images && typeof imgUrl != 'undefined')
      document[imgName].src = imgUrl.src;
  }
// -->
</script>  

The first line (the if statement), checks to make sure the specified Image object exists. The reason for this check is because the user's Web browser may have only downloaded part of the HTML document when this display() function gets called. If this is the case, the JavaScript for loading the images might yet to have been downloaded, in which case trying to access the Image object's src property would result in a JavaScript error.

If this check passes, however, the specified <img> tag has its src property set to the src property of the specified Image object.

The last step to creating a roll-over button is to tie the display() function with the mouse entering and leaving the button. To do this, you need to add onmouseover and onmouseout event handlers to the <a> tag. These event handlers need to call the display() function, passing in the correct parameters. The complete HTML for the roll-over button (less the JavaScript examined above), is shown below:

<a href="..."
     onmouseover="display('home_img', home_img_over);"
     onmouseout="display('home_img', home_img_out);"
    >
  <img src="home.gif" name="home_img" border="0" />
</a>
[View a Live Demo!]

Note that the onmouseover and onmouseout event handlers simply call display() passing in the name of the <img> tag and the name of the Image object to display. To see the complete source code all in one place, refer to the live demo.

Creating a Roll-Over Button Server Control
Doing a bit of research I found an existing (free) roll-over button control on MetaBuilders.com called RollOverLink. This server control displays a roll-over button that, when clicked, whisks the user to a specified URL, much like the ASP.NET HyperLink Web control. (In fact, the RollOverLink control is derived from the System.Web.UI.WebControls.HyperLink class.) While this control is great if you need hyperlink-like behavior with a Web control, there are times where might want a roll-over button to behave like a Button Web control - that is, clicking the button causes a postback rather than taking the user to a specified URL. Since I could not find such a control online, I decided to create my own. (The remainder of the article focuses on building the roll-over button server control, one that causes a postback; if you just want the roll-over button to send the user to a specified URL when clicked, I encourage you to utilize RollOverLink.)

The beautiful thing about object-oriented programming is that it encourages reuse. The whole idea behind inheritance is that you can build classes that provide some base functionality, and then create other classes that extend the functionality present in the base classes. (If you are unfamiliar with object-oriented programming or inheritance, I invite you to read Ian Stalling's Using Object-Orientation in ASP.NET: Inheritance.) Realize that there is already an ASP.NET Web control that does almost exactly what we want our roll-over button to do: the LinkButton control.

The LinkButton control renders as a hyperlink. When clicked, the hyperlink causes the page to postback (as opposed to taking the user to a specified URL). Therefore, all we need to do is create a control that derives from LinkButton, add properties for the default image URL and the roll-over image URL, have the control emit a bit of client-side script, and then (finally), override the RenderContents() method so that our roll-over button generates the HTML for an <img> tag inside the <a> tag (as opposed to merely displaying the Text property, which is what the LinkButton does).

Let's examine each of these steps individually. Before we do so, though, let's first take a look at the shell of the class for our server control:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace RolloverButton
{
	[ToolboxData("<{0}:RollOver runat=server></{0}:RollOver>")]
	public class RollOver : System.Web.UI.WebControls.LinkButton
	{

	}
}

Here you can see that the class is derived from System.Web.UI.WebControls.LinkButton. Also note that the class's name is RollOver, and the namespace is RolloverButton. In Part 2 we'll examine the steps needed to create the server control in detail.

  • Read Part 2!


    Windows Internet Technology | ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article



  • JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Windows Server 2008
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES