GROVER.
GROVER.

Reputation: 4378

input not adding class when focused

I have this extremely simple click event, where if the input has been focused, it is supposed to add a class to said input.

However, it doesn't want to add the class. I have been sure to include the jQuery library, but nothing happens.

jQuery:

$("body").on("click", function(){
    if($("input").is(":focus")){
        $(this).addClass("highlight-input");
    } else {
        $(this).removeClass("highlight-input");
    }
});

Upvotes: 2

Views: 57

Answers (2)

Dekel
Dekel

Reputation: 62576

In your code - this denotes the body element, so when you use $(this).addClass("highlight-input"); you add the highlight-input class to the body element.

$("body").on("click", function(){
    if($("input").is(":focus")){
      debugger;
      $(this).addClass("highlight-input");
    } else {
        $(this).removeClass("highlight-input");
    }
});
.highlight-input {
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input />

This is more likely what you are looking for:

$('input').on('focus', function() {
  $(this).addClass("highlight-input");
}).on('blur', function() {
  $(this).removeClass("highlight-input");
});
.highlight-input {
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input />

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

You need to use this way:

$(document).ready(function () {
  $("input").on("focus", function () {
    $(this).addClass("highlight-input");
  }).on("blur", function () {
    $(this).removeClass("highlight-input");
  });
});

Upvotes: 2

Related Questions