This is a really simple thing that I’m sure dozens of other people have already implemented over and over by now and that’s not counting the hundreds whose Mephisto theme doesn’t do this out of the box.
Basically I wanted my new theme, wibbish, to have some sort of label for the search box. Here’s my take on creating an unobtrusive default for the form field like you see on many sites these days. The idea is simple, when the form field is not focused and has no user entered value, it should have a CSS class appended to it so that its styling clearly indicates it’s in a default state while at the same time have its value set to some sane value that would work as a label in a traditional form layout. Once the field becomes focused, that new CSS class and default value should be removed to make it easier to modify the form field.
Now to cut to the chase, here’s the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
Event.observe(window, 'load', function() { // grab a reference to the search field var q = $('q'); // add a focus and blur handler to the search field Object.extend(q, { // set the default text as an attribute of the object so it's only set once defaultText: 'Search', // simple onBlur handler to add a "default" class and text to the field onBlur: function() { if (this.value == '') this.addClassName('default').value = this.defaultText; }, // simple onFocus handlers to remove the "default" class and text from the field onFocus: function() { if (this.value == this.defaultText) this.removeClassName('default').clear(); } }); // attach our handlers q.observe('blur', q.onBlur.bindAsEventListener(q)).observe('focus', q.onFocus.bindAsEventListener(q)); // finally just trigger the onBlur event handler to initialize everything q.onBlur(); }); |
Of course, now that I’m done with this, it’s time to try writing a plugin or patching Mephisto to have an unobtrusive live search.
Update: As if it wasn’t obvious, this is all based upon the excellent prototype library.
