Better JavaScript programmer

Following code follows some nice JavaScript idioms:
InputHint = {
    std_color: '#000',
    help_color: '#555',

    attach: function(input, text, def_value) {
        input.value = def_value || '';

        var check_fn = $p($b(this._check, this), input, text);
        AEV(input, 'blur', check_fn);
        AEV(input, 'focus', check_fn);

        check_fn();
    },

    _check: function(input, text) {
        if(input.value == '') {
            input.value = text;
            input.style.color = this.help_color;
        }
        else if(input.value == text) {
            input.value = '';
            input.style.color = this.std_color;
        }
        else {
            input.style.color = this.std_color;
        }
    }
}

Following things are great about the code above:

  • A JavaScript library is used - AJS in this case
  • Global scope isn't polluted - crucial if you write lots of JavaScript code!
  • Local variables are declared using var - great for performance and non global scope pollution
  • Code is indented and structured - makes it readable
  • Code follows a naming convention (local_variables, ClassName, methodName)

Easy tips that can help your JavaScripting a lot.

Code · Code improvement · JavaScript · Tips 20. Jan 2008
© Amir Salihefendic. Powered by Skeletonz.