Sponsored

Wednesday, March 11, 2009

Using ColorPickerExtender Client-side Events

There have been question about how to utilize the client-side functionality of the ColorPickerExtender in order to improve customer experience. Here is an example of how to use a colorSelectionChanged client event.

Subscribing to the colorSelectionChanged event

You can subscribe to the event either via JavaScript code or ASP.NET mark-up:

    var cpe = $find("ColorPickerExtender1");
    cpe.add_colorSelectionChanged(changeColor);

Here $find is a standard function of the ASP.NET AJAX Framework that returns an instance of the AJAX component by BehaviourID; ColorPickerExtender1 is a BehaviourID of the ColorPickerExtender component and changeColor is your JavaScript function that will be called when the event occurs.

<ajaxToolkit:ColorPickerExtender ID="defaultCPE" runat="server"
TargetControlID="Color1"
    BehaviorID="ColorPicker1"
    OnClientColorSelectionChanged="changeColor"
/>

Make sure that the changeColor JavaScript function exists on the page otherwise you'll see a JavaScript error "changeColor is undefined". You may define a changeColor function like this:

function changeColor(sender) {
    sender.get_element().style.color = "#" + sender.get_selectedColor();
}

When your function is called after a user picked a color (i.e. clicked a mouse on the color palette) a sender argument will point to the instance of the ColorPickerExtender component that you can use inside your function. For instance, call a method get_element() to retrieve a reference to an input DOM element which the extender is attached to or use a get_selectedColor() method to retrieve a hexadecimal color code that the user selected. When assigning the color value to a DOM element style don't forget to prepend it with a '#' character.

2 comments:

  1. This does not work:

    sender.get_selectedColor();

    "Microsoft JScript runtime error: Object doesn't support this property or method"

    ReplyDelete
  2. To Nearby Caper: what version of the ACT are you using? Could you provide a longer example of the actual JavaScript code?

    ReplyDelete