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.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework