Home »
jQuery »
jQuery Examples
Using jQuery to test if an input has focus
Learn, how to check whether the input field has been focussed or not using jQuery?
Submitted by Pratishtha Saxena, on November 21, 2022
The focus() method is a inbuilt jQuery method which helps to achieve the focus of the selected element. To achieve the focus here means that – the method will get the cursor blinking on the selected element (input tag). When we are not writing in the input field, the cursor is inactive. As soon as we click in the input field achieves the focus, i.e., it gets focused.
Generally, this is used with the input tag of the form element, but now it can be implemented by all the other elements too.
Syntax:
$('selector').focus();
$('selector').focus(function);
It takes one optional parameter – function. The function is the custom function that can be defined to do some tasks when this method gets triggered.
The following example shows how can we test different input fields and whether they have been focused or not. Whenever the input field is focused, we’ll attach a class, with some background color, to it. Hence, the input field with the colored background can be said as 'focused'.
jQuery code to test if an input has focus
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Document</title>
<style>
.focus{
background-color: cadetblue;
}
</style>
</head>
<body>
<h2>Using jQuery to test if an input has focus</h2>
<p>Click different input fields to activate them and get focused.</p>
<hr>
<b>
Name: <input type="text"><br><br>
Email: <input type="email"><br><br>
Contact: <input type="number"><br><br>
Gender:</b> <input type="radio" name="gender">Female
<input type="radio" name="gender">Male
<hr>
</body>
<script type="text/javascript">
$(document).ready(function(){
$('input').focus(function(){
// it will remove the class from the previous
// input filed to the focussed one.
$('input').removeClass();
$(this).toggleClass('focus');
});
});
</script>
</html>
Output: