Skip to main content

Changing form input styles on focus with jQuery.

// Changing Form Input Styles on Focus with jQuery
// my minor mod'd version of: http://buildinternet.com/2009/01/changing-form-input-styles-on-focus-with-jquery/

/* CSS
---------------------------------------------------------------- 

*{
  margin:0;
  padding:0;
  font:bold 12px "Lucida Grande", Arial, sans-serif;
}

body {
  padding: 10px;
}

#status{
  width:50%;
  padding:10px;
  outline:none;
  height:36px;
}

.focusField{
  border:solid 2px #73A6FF;
  background:#EFF5FF;
  color:#000;
}

.idleField{
  background:#EEE;
  color: #6F6F6F;
  border: solid 2px #DFDFDF;
}

---------------------------------------------------------------- */

$(document).ready(function () {
  // For every text input apply the class idleField to it
    $('input[type="text"]').addClass("idleField");

  // When a text input gets focus, remove the inactive style and add the active style.
    $('input[type="text"]').focus(function () {
        $(this).removeClass("idleField").addClass("focusField");
    
        if (this.value == this.defaultValue) {
            this.value = '';
        }
        if (this.value != this.defaultValue) {
            this.select();
        }
    });

    $('input[type="text"]').blur(function () {
        $(this).removeClass("focusField").addClass("idleField");

        if ($.trim(this.value) === '') {
            this.value = (this.defaultValue ? this.defaultValue : '');
        }
    });

});