In this lesson, you will learn how to use focus event in jQuery to make web pages more interactive and alive.

Introduction to Focus event in jQuery

When a user clicks or tabs on a text field, it gets focused. In other words, it gets the web browser’s attention. This event is used mostly when you need to create some effects or animations around the text field being focused or clicked.

The syntax of the focus event is:

.focus( function(){});

The function is the handler, which executes every time the focus event is being triggered. You can even use this function without any arguments or function being called.

This is a short form of writing .on("focus", function(0{});.

You can apply focus event on a limited number of web elements, such as input, select, etc.

Example of Focus event in jQuery

In this example, we will create a form that has two text fields and one submit button. The first field called ‘uname’ has a default value “Your name”. When the user clicks on the ‘uname’ field, the default value will be replaced by an empty string so the user can enter his/her name.

Focus event Example


<div id="container">
   <form action="">
      <label for="uname">Your Name</label>
      <input type="text" name="uname" id="uname" value="Your name"><br><br>
      <label for="number">Phone Number</label>
      <input type="text" name="number" id="number"><br><br>
      <input type="submit" name="submit" value="submit">


#container {
	margin: 20px;
	padding: 10px;
	border: 1px solid #ccc;
	width: 400px;

label {
	width: 100px;
	display: block;

input {
	width: 80%;

The jQuery

<script src = "" ></script> 
    $(document).ready(function() {
        $("#uname").focus(function() {
            var uname = $(this);
            if (uname.val() == "Your name") {


The ‘if’ condition in the jQuery code ensures that the user will get the empty field only once when the string value is equal to the default value.

jQuery Blur Event Tutorial Home jQuery Submit Event


Last modified: July 8, 2019


Write a Reply or Comment

Your email address will not be published.