HTML and CSS Reference
In-Depth Information
The “whenever anything
changes” event
One almost insignificant change to the <form> element is a new
event called oninput . In fact, this is a useful event that fires on
the form element when any of the form fields within the form
change. This saves you having to attach lots of onchange han-
dlers to each form control.
For instance, if I were to create a colour picker that gives me
both RGBA and HSLA, typically I would have to hook event lis-
teners to each of the value sliders. By using the oninputchange
event, I'm able to hook a single event listener to the form and
recalculate my RGBA and HSLA values using a single method.
Whether I'm attaching lots of event listeners or just a single one,
the result is very similar. However, this feels a lot cleaner and
better designed, as there's no duplication of event listeners.
When a slider is changed, it generates the RGBA and HSLA and
update the preview colour. The code listing below is just the
JavaScript required:
form.oninput = function () {
var i = this.length, values = [], value = 0;
while (i--, value = this[i].value) {
if (this[i].type == 'range') {
switch (this[i].name) {
// alpha_channel is between 0-1
case 'alpha_channel': values.push(value / 100);
¬ break;
// hue is a plain value from 0-360
case 'hue': values.push(value); break;
// default includes saturation & luminance as a
¬ percentage
default: values.push(value + '%');
hsla.value = 'hsla(' + values.reverse().join(', ') + ')'; = hsla.value;
rgba.value = getComputedStyle(preview, null).
¬ backgroundColor;
NoTE In the first edition
of this topic, we talked
about onforminput , but since
then the event handler has been
deprecated. But fear not, this
section remains valid, because
the very similar oninput event
handler is part of HTML5 and
we can use it in a very similar
way to onforminput .
Search WWH ::

Custom Search