jQuery Events: Test if an input has focus
jQuery Events : Exercise - 19 with Solution
Test if an input has focus?
HTML code:
<body> <div id="content"> <input tabIndex="1"> <select tabIndex="3"> <option>select menu</option> </select> <p tabIndex="3"> A Paragraph </div> </div> </body>
CSS Code for focused color :
<style> .focused { background: green; } </style>
Solution:
HTML Code:
<!DOCTYPE html>
<html>
<head>
<style>
.focused {
background: green;
}
</style>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>Test if an input has focus</title>
</head>
<body>
<div id="content">
<input tabIndex="1">
<select tabIndex="3">
<option>select menu</option>
</select>
<p tabIndex="3">
A Paragraph
</div>
</div>
</body>
</html>
CSS Code:
.focused {
background: green;
}
JavaScript Code:
$( "#content" ).delegate( "*", "focus blur", function() {
var elem = $( this );
setTimeout(function() {
elem.toggleClass( "focused", elem.is( ":focus" ) );
}, 0 );
});
Live Demo:
See the Pen jquery-events-exercise-19 by w3resource (@w3resource) on CodePen.
Contribute your code and comments through Disqus.
Previous: Set the focus to the first input box.
Next: Set background color of an element when the element (or any elements inside it) gets focus or loses focus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/jquery-exercises/jquery-events-exercise-19.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics