Focus first 'focus'able form field on load (DOM)


/ Published in: JavaScript
Save to your folder(s)

Usage:

//any element
window.onload = function(){
focusFirstInput();
}

or

// form elements under 'content-body'
window.onload = function(){
focusFirstInput('content-body');
}


Copy this code and paste it in your HTML
  1. var focusFirstInput = function(obj) {
  2. var forms = (obj && document.getElementById(obj)) ? document.getElementById(obj).getElementsByTagName('form') : document.forms;
  3.  
  4. if (forms.length > 0 && document.forms[0].elements[0]){
  5. var eltype = document.forms[0].elements[0].type;
  6. (eltype=="text" || eltype=="textarea" || eltype=="select-one" || eltype=="select-multiple" || eltype=="password") ? forms[0].elements[0].focus() : null;
  7. }
  8. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.