Monday, August 6, 2007

onChange handler for the colorpicker

Knallgrau's color picker has been a really useful library, but it took a bit to figure out syntax for the onchange handler. Each colorbox shares the same colorpicker, so I was having trouble deciphering which of the DOM elements was the calling element, so I set an 'onclick' handler on the 'ok' button then had a big loop through all the possible elements to see which one changed. Besides being ugly, the user doesn't have to click on the 'ok' button to exit the colorpicker, so this implementation fails to register a lot of events.

Turns out I was going about this all the wrong way. Knallgrau has an 'onUpdate' attribute that you can set. Here's the syntax when initializing the colorpicker:

new Control.ColorPicker("inputid", { IMAGE_BASE : "javascripts/colorpicker/img/", "swatch" : "buttonid", "onUpdate" : changeColor });

where 'inputid' is the id of the <input> element, 'buttonid' is the id of the <button> element, and 'changeColor' is the function called when the color is updated.

In the changeColor function, this.field gives you the input element. Example:

function changeColor ()
console.log (this.field); //prints <input type="hidden" id="hapcolor1" name="hapcolor1" value="B71919"/>

console.log (; //prints "inputid"

No comments: