jQuery Events: Set background color of an element when the element gets focus or loses focus
jQuery Events : Exercise - 20 with Solution
Set background color of an element when the element (or any elements inside it) gets focus or loses focus.HTML code:
<body> <div> First name: <input type="text"><br> Last name: <input type="text"> </div> </body>
CSS Code for focused color :
<style> .focusedin { background: green; } .focusedout { background: blue; } </style>
Solution:
HTML Code:
<!DOCTYPE html>
<html>
<head>
<style>
.focusedin {
background: green;
}
.focusedout {
background: blue;
}
</style>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>Set background color of an element when the element gets focus or loses focus</title>
</head>
<body>
<div>
First name: <input type="text"><br>
Last name: <input type="text">
</div>
</body>
</html>
CSS Code:
.focusedin {
background: green;
}
.focusedout {
background: blue;
}
JavaScript Code :
$("div").focusin(function(){
$(this).attr('class', 'focusedin');
});
$("div").focusout(function(){
$(this).attr('class', 'focusedout');
});
Live Demo:
See the Pen jquery-events-exercise-20 by w3resource (@w3resource) on CodePen.
Contribute your code and comments through Disqus.
Previous: Test if an input has focus?
Next: Display the tag name of the clicked element.
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-20.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics