Monday, September 1, 2014

Set focus on first visible element using Javascript

Here is the Javascript code, you can use to set the focus of cursor on first visible element of the page.


function SetDefaultFocus()
{
    try
    {
        //loop will work for each form on the page
        for (f=0; f < document.forms.length; f++)
        {
           // for each element in each form
            for(i=0; i < document.forms[f].length; i++)
            {
              // if it's not a hidden element and it's not disabled
              if (document.forms[f][i].type != "hidden" && document.forms[f][i].disabled != true)
              {    
                    document.forms[f][i].focus();
                    return;
              }    
            }//eof sub-for  
        }//eof main for
    }
    catch(e)
    {
     
    }
}

Only you have to call this method on window onload or in jquery ready methods, This will automatically set the focus to that position.

Happy Coding!!

No comments:

Post a Comment