user2565192
user2565192

Reputation: 654

Why my focus() in jquery not working?

I want to change the color of the text box in html when on focus. But my color is not changing.!

Html

<!DOCTYPE html>
<html>
 <head>
  <title>Make a new account</title>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
   <script src="script.js" type="text/javascript" ></script>
 </head>
 <body>
  <h2 align="center" class="Heading">Want an account</h2>
  <h3 align="center" class="Heading">Enter your details</h3>
  <div align="center">
   <form name="Info_Form">
    <table>
     <tr>
      <td class="TD">Your Name Pal :</td> <td><input type="text" name="Name"></td>
     </tr>
     <tr>
      <td class="TD">Your Password :</td> <td><input type="password" name="pwd"></td>
     </tr>
     <tr>
      <td align="right" ><input type="submit" value="Submit"></td>
     </tr>
    </table>
   </form>
  </div>
 </body>
</html>

my js file:

$(document).ready(function(){
 $('h2').fadeOut(3000);
 $(".TD").focus(function(){
    $(this).css("background-color","blue");
  });
});

What am i doing wrong?

Upvotes: 2

Views: 923

Answers (2)

poorvank
poorvank

Reputation: 7602

Instead of :

$(".TD").focus(function(){
    $(this).css("background-color","blue");
  });

Use:

$("input").focus(function(){
    $(this).css("background-color","blue");
  });

Upvotes: 2

Elorfin
Elorfin

Reputation: 2497

It's because you can apply .focus() to only a limited number of element (links, form inputs).

From jQuery documentation :

The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (, , etc.) and links (). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.

Here you try to apply it to a <td> tag.

Moreover, your <input> is not a child of .TD, so it's another problem in your code.

Why not simply use css :focus selector to achieve this ?

Upvotes: 2

Related Questions