Chain Trap Chain Trap - 1 year ago 204
Javascript Question

JavaScript - Get current focused element that hasClass() with jQuery

I know this is just a simple question for you but here I'm having a hard time trying to solve my own problem.

In my case, I have several text field that changes color of the field's border and label's text when the field itself is focused, and will revert changes when it is not focused. So then I used the following code: (see my demo)

$(function() {
$(".field").focus(function() { /* ... */ });
$(".field").blur(function() { /* ... */ });

But since I'm pointing to the class
, all elements that have this class will be affected so I thought I have to set the current active element with the class
so the other elements will be excluded. I used the below code but it doesn't work (and I don't even know if I'm right about the idea):

var current = $(document.activeElement).hasClass(".field");
$(current).focus(function() { /* ... */ });
$(current).blur(function() { /* ... */ });

If there's another way to settle this please tell me how.

Hope you could help me.


Answer Source

You can update your $(".field") selector to $(this) to select the field and $(this).next() to select the field's label inside both your blur and focus functions. Only the selected field and the next label will be selected, see this snippet:

$(function() {
  $(".field").focus(function() {
    /* when field with or without value is focused, add these classes */
    if ($(this).val().length || $(".field").val().length == "") {
  $(".field").blur(function() {
    /* when field with or without value is not focused, remove added classes */
    if ($(this).val().length || $(".field").val().length == "") {
fieldset {
  border: 2px solid #ccc;
  padding-top: 20px;
  padding-bottom: 20px;
.label {
  float: left;
  margin-right: 5px;
.field {
  border: 2px solid #ccc;
  padding: 0 5px;
  height: 22px;
  margin-bottom: 10px;
.field:focus {
  outline: 0;
  outline-offset: 0;


.field-is-focused {
  border-color: blue;
.label-is-focused {
  color: blue;
<script src=""></script>
<!DOCTYPE html>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width"/>
	<title>jQuery - Get current focused element</title>
        <script src=""></script>
		<!-- input email type field -->
		<input type="email" class="field">
		<label class="label">Email</label>

		<!-- input password type field -->
		<input type="password" class="field">
		<label class="label">Password</label>
		<!-- textarea field -->
		<textarea class="field"></textarea>
		<label class="label">Comment</label>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download