Posts Tagged ‘css’

Stylizing text input elements with background images

Saturday, October 11th, 2008

I often like to add background images to my text input elements, it’s a great way to stylize them and adds a nice little pop to small forms. The search box in the upper right corner of this blog is an example of this. I recently wrote this nice little javascript function to help me get this done quickly and easily.

Feel free to use this code wherever you please, it requires the prototype javascript library.  There’s an example of the usage at the bottom.

crabenda.global.giveTextInputBackground = (function(){
handleFocus = function(e){
elem = Event.element(e);
elem.setStyle({’background’: ‘none’});
}
handleBlur = function(e){
elem = Event.element(e);
if(elem.value === ”){
elem.setStyle({’background’: ‘url(’+elem.backgroundImgSrc+’) no-repeat’});
}
}
return function(formElem,imgSrc){
formElem = $(formElem);
if(formElem){
formElem.backgroundImgSrc = imgSrc;
Event.observe(formElem,’focus’,handleFocus);
Event.observe(formElem,’blur’,handleBlur);
if(formElem.value === ”){
formElem.setStyle({’background’: ‘url(’+formElem.backgroundImgSrc+’) no-repeat’});
}
}
}
})();

Sample usage:

document.observe(”dom:loaded”,function(){
Event.observe(’submitbutton’,'click’,crabenda.header.submitButtonClickHandler);/search3.gif’)
});

If any of the code looks odd(like maybe the parentheses before and after the function) then you need to watch more Douglas Crockford!
Cheers!