Wednesday, October 15, 2014

Set Cursor To Image From Code Behind

Changing the cursor to something unexpected is not a good idea most of the time because it may confuse your users. However, there may be times when it fits the situation well.

This is how I do it using ASP.NET and C#.   The basic idea is to create a class with the cursor property set to an image and then add that class to a div from code behind.

In this example,  I'm using FormsAuthentication and I want to change the cursor only when "chuck" is logged in.

CSS

Create a class definition for chuck like the following.

 .chuck{ cursor: url(../images/littleChuck.png), auto; }

A couple of things to note here:
  • Use a small image. Don't exceed 32px in length or width
  • Use a url path relative to the page using the image, not relative to the css file.
  • Always follow the url() with auto. Just two values --> cursor: url(), auto;

Identify the div to Apply Cursor

You need something to apply the css class to in the code behind. Let's use a div for this example.

Don't forget to use the runat="server" on the div so we can access the div from the code behind.

<div id="wrapper"   runat="server" > 

</div>

C# in Code Behind

Add the "chuck" class to the wrapper div if the logged in user name is "chuck".

if(HttpContext.Current.User.Identity.Name.ToLower() == "chuck" )
{
       wrapper.Attributes.Add("class", "chuck");
}


Summary

Changing the cursor to image is only one of many values that can be applied.  Check out this link at w3schools to experiment with the 30+ values.

Visit Blue Canyon Software if you need a Senior Software Developer for your custom software project.


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.