mootools and form field hints

Usually I love mootools, really. Usually. I found CSS Guy’s form field hints posting inspiring, so I modified it to work with mootools. The result is something simple and easy.

$ES('div.hint').each(function(el) {
	new Element('div').addClass('hint-pointer').setHTML(' ').injectInside(el);
});
$each(document.forms, function(form) {
	$each($(form).getElementsBySelector('input, select'), function(input) {
		if($(input).getParent().getElementsByTagName('div')[0]) {
		$(input).addEvent('focus', function(e) {
			hint = $E('.hint', this.getParent());
			hint.setStyle('display', 'inline');
			hint.effect('opacity', {duration: 500, wait: false}).set(0).start(1);
		}.bind(input));
		$(input).addEvent('blur', function(e) {
			hint = $E('.hint', this.getParent());
			hint.effect('opacity', {duration: 500, wait: false}).set(1).start(0);
		}.bind(input));
		}
	});
});

I modified the CSS to suit my layouts better. You’ll notice above I am using divs instead of spans. I noticed IE6 would never hide the hints div ever again once it was diplayed. Fortunately the fade effect hides it for me.

.hint {
	display: none;
	position: absolute;
	right: 1em;
	border: 1px solid #c93;
	padding: 0.4em 0.5em;
	background-color: #ffc;
	font-size: 80%;
}
.hint .hint-pointer {
    position: absolute;
    left: -10px;
    top: 2px;
    width: 10px;
    height: 19px;
    background: url(/images/pointer.gif) left top no-repeat;
}

The mootools bonus: I can easily add a fade effect, which I did. I further simplified things by adding the hint-pointer div at render time with mootools instead of repeating the markup over and over again. A little DRY from Rubyland.

Yay.

2 Comments

  1. Posted 8/29/2007 at 7:54 am | Permalink

    Some hints for shorter and faster code
    - No need to use $ on input all the time, its extended one time from getElementsBySelector.
    - Don’t use $ES, use $$ or el.getElements, $ES is deprecated in 1.2dev, also the second argument for $E. All in favour of Element::getElement and getElements
    - You don’t need $each, u can use the Array::each: $$(document.forms).each(… … form.getElementsBySelector(’input, select’).each( …
    - You never declare var hint, so hint is a global scope, bad idea
    - No need to bind input to the event callback, this in an event callback is always the element

  2. Posted 9/10/2007 at 5:15 pm | Permalink

    Thanks!

    I ended up using $ on input because IE kept complaining about a missing function or something. Adding that seemed to get it working in IE, though debugging IE is so frustrating it’s possible something else I did resolved it.

Post a Comment

Your email is never shared. Required fields are marked *

*
*