1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

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?
    SEMrush
     
    piniyini, Apr 23, 2006 IP
    SEMrush
  2. Logic Ali

    Logic Ali Active Member

    Messages:
    170
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    58
    #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