Mar 22

Textbox label inside

Posted By Ahmed El-Kilani On 22 Mar 2008 No Comments »
Sometimes labels beside textboxes require much space and bad design, so the best solution is to type the label text inside the textbox, it is pretty easy but we need some retouch, like coloring the label text with a different color and handle onfocus and onblur events.
Here is a javascript function that does this for you:
    function labelText(id , text)
    {    
        var element = document.getElementById(id);
        var labelColor = 'gray';
        var originalColor = 'black';
        if(element.style.color)
            originalColor = element.style.color;
        
        element.style.color = labelColor;
        element.value = text;
        element.isNull = true;
               
        element.onblur = function(){
            if(this.value.replace(' ','') == '')
            {
                this.value = text;
                this.isNull = true;
                this.style.color = labelColor;
            }
        }
        element.onfocus = function(){
            if(this.isNull)
            {
                this.value = '';
                this.isNull = false;
                this.style.color = originalColor;
            }
        }
        
    }
    
And easily you can label any input field like:
    
    
    labelText('myText' , 'Search...');