Get focused element in jquery

Mainly jQuery .focus() event is used to get focused element, but what if we have a chain of elements in a single .focus() event? In this post i simple describe that how do we get focused element with jquery in a chain of elements with the use of .focus() event. As you see below highlighted codes i show you both the jquery section and the html section, First i want to describe the html section, in the HTML section in also mentioned the ID of the the input element, all the ID’s are different according to the input element.

Now lets move to the jQuery section, i have taken to variables the first one for the element id and the second element for the focus, i make that variable by default false. Now take all the elements and apply the .focus() event on that elements like the below codes. Now all work with in the .focus() element. I have used this.id to get the current focused element ID and set that ID in the variable. After that check all the different cases in the switch statement to match the correct focused element. Hope you all enjoying with this code. And if you really enjoying with this article or have better alternatives then please leave a comment regarding this article.

JQuery section:

$(document).ready(function(){

var _elementID,
_focus = false;

// Set .focus() event on elements
jQuery('input[name="fname"], input[name="lname"], input[name="email"]').focus(function(){

// Get ID of the focused element
_elementID = this.id;
_focus = true;

switch( _elementID ){
case 'fname':
// Do Action
alert( _elementID );
break;<a href="http://demo.webtech11.com/page/get-focused-element-in-jquery/index.html" title="demo" target="_blank"></a>
case 'lname':
// Do Action
alert( _elementID );
break;
case 'email':
// Do Action
alert( _elementID );
break;
}
});
});

 

HTML Section:

<form>
<table cellpadding="6" cellspacing="" style="border-collapse:collapse;">
<tr>
<td>
<label>First Name :</label>
</td>
<td>
<input type="text" name="fname" id="fname" />
</td>
</tr>
<tr>
<td>
<label>Last Name :</label>
</td>
<td>
<input type="text" name="fname" id="lname" />
</td>
</tr>
<tr>
<td>
<label>Email :</label>
</td>
<td>
<input type="text" name="fname" id="email" />
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>
<input type="button" class="button" name="submit" value="Register" />
</td>
</tr>
</table>
</form>

 

Posted by Jogesh Sharma

Jogesh Sharma is a web developer and blogger who loves all the things design and the technology, He love all the things having to do with PHP, WordPress, Joomla, Magento, Durpal, Codeigniter, jQuery, HTML5 etc. He is the author of this blog.