w3resource

jQuery: Attach a function to the focus event

jQuery Events : Exercise-17 with Solution

Attach a function to the focus event. The focus event occurs (display a message regarding the text field) when the <input> field gets focus.

Sample Data :

<body>
<p><input type="text"> <span>Input your first name</span></p>
<p><input type="text"> <span>Input your last name</span></p>
</body>

Solution:

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>Attach a function to the focus event</title>
</head>
<body>
<p><input type="text"> <span>Input your first name</span></p>
<p><input type="text"> <span>Input your last name</span></p>
</body>
</html>

CSS Code:

span {
    display: none;
  }

JavaScript Code :

$( "input" ).focus(function() {
  $( this ).next( "span" ).css( "display", "inline" ).fadeOut(5000);
});

Live Demo:

See the Pen jquery-events-exercise-17 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Display the keyboard key which was pressed in a textbox.
Next: Set the focus to the first input box.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.