Check if a input field is focused?

Discussion in 'JavaScript' started by piniyini, Apr 23, 2006.

  1. #1
    I've searched all over for this and can't find a solution. Anyone know how to check if a input field is focused or not?
     
    piniyini, Apr 23, 2006 IP
  2. Logic Ali

    Logic Ali Well-Known Member

    Messages:
    170
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    108
    #2
    There's no built-in way; you have to use the onfocus and onblur events to
    set some form of flag for each element to be read.

    This script automates the process for any number of forms:

    
    <script type='text/javascript' >
    /* (c)2006 Stephen Chalmers
     * 
     * Appends a 'hasFocus' flag to all text/textarea form
     * elements.
     *
     
    Insert this script anywhere below the last form in the document.
    
    To read the current focus state of a specified element, use:
    
    if( document.forms.myForm.myElement.hasFocus )
     ...
    
    ***/
    
    for(var i=0, df=document.forms, len=df.length; i<len; i++)
     for(j=0, els=df[i].elements; j<els.length; j++)
      if( /^text/.test( els[j].type ) )
      {
       els[j].hasFocus=false;
       els[j].onfocus=function(){this.hasFocus=true;};
       els[j].onblur =function(){this.hasFocus=false;};
      }
    
    </script>
    
    Code (markup):
     
    Logic Ali, Apr 24, 2006 IP