jQuery focus() Method

jQuery focus() method trigger the focus event. The jQuery focus event occurs when an element gets focus. And when the focus event occurs, specified function will execute.

Syntax

This triggers the focus event for selected elements.

$(selector).focus();        // This syntax does not accept any arguments.

This attach a function to the focus event.

$(selector).focus(function);
Parameter Type Description
function Function Optional. Specifies the function to execute when the focus event is occurs.

Examples

This example represents the focus() event.

$(document).ready(function(){
  $(".btn1").click(function(){
    $("input").focus();
    $("input").css("background-color", "yellow");
  });  
  $(".btn2").click(function(){
    $("input").blur();
    $("input").css("background-color", "white");
  });
});

Run it...   »


This example represent to attach a function to the focus() event.

$(document).ready(function(){
  $("input").focus(function(){
    $(this).css("background-color", "yellow");
  });  
  $("input").blur(function(){
    $(this).css("background-color", "white");
  });
});

Run it...   »