Focus event in jQuery


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

The HTML

<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">
   </form>
</div>

The CSS

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

label {
	width: 100px;
	display: block;
}

input {
	width: 80%;
}

The jQuery

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js" ></script> 
    <script>
    $(document).ready(function() {
        $("#uname").focus(function() {
            var uname = $(this);
            if (uname.val() == "Your name") {
                uname.val('');
            }

        });
    }); 
    </script>

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

 

Tutorials Panel

About Tutorials Panel

programming tutorial and source code for Software Engineers and developers. https://twitter.com/TutorialsPanel

View all posts by Tutorials Panel →

Leave a Reply