JQuery Forms Focus

From CoderLearner
Jump to: navigation, search

Description

Bind an event on the focus JavaScript event.

Syntax

$.focus( handler(eventObject) );

$.focus( [eventData], handler(eventObject) );

$.focus();

Example 1

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>serializeJSON</title>
        <script 
            type="text/javascript" 
            src="jquery.min.js">				 
        </script>
        <script>
            $().ready(function() {
              $('#first').focus(function(){
                  $('span').html("<label> First Name </label>");
              });
            });
        </script>
    </head>
    <body> 
        <form>
            <input type="text" name="first" id="first"/><span></span>     
        </form>
    </body>
</html>

Try It

Example 2

Set background when the element is in focus.

$(document).ready(function() {
                $("#first").focus(function () {
                    $(this).css("background","#ab3959");
                });
});

<input type="text" name="first" id="first"/>

Try It

Example 3

Add the focus event to all element has focus.

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Focus</title>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <style>
            .focused {background: #D34040;}
        </style>
        <script>
            $(document).ready(function() {
                $('form').on('focus blur','input',function(){
                    var elem = $( this );
                    setTimeout(function() {
                        elem.toggleClass( "focused", elem.is( ":focus" ) );
                    }, 0);
                });
            });
        </script>
    </head>
    <body> 
        <form>
            <p><input type="text" name="first" id="first"/></p>     
            <p><input type="text" name="second" id="second"/></p>
        </form>
    </body>
</html>

Try It