Reputation: 197
I'm just calling a function highlightInput(this)
which is just changing colors for selected input. I think there might be a better way to avoid repetition. Any ideas?
HTML file
<div class="form-group">
<label for="your_name">Your name:</label>
<input type="text" class="form-control" name="your_name" onfocus="highlightInput(this);">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" name="email"onfocus="highlightInput(this);">
</div>
<div class="form-group">
<label for="title">Event title:</label>
<input type="text" class="form-control" name="title"onfocus="highlightInput(this);">
</div>
<div class="form-group">
<label for="location">Event location:</label>
<input type="text" class="form-control" name="location"onfocus="highlightInput(this);">
</div>
var Color = {
inputColor:function (color, self){
$(self).css('backgroundColor', color);
}
}
function highlightInput(self){
Color.inputColor('lightyellow', self);
$(self).blur(function(){
Color.inputColor('white', self);
});
}
Upvotes: 1
Views: 109
Reputation: 5264
$('input.form-control').blur(function() {
this.style.backgroundColor = 'white';
});
$('input.form-control').focus(function() {
this.style.backgroundColor = 'lightyellow';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="your_name">Your name:</label>
<input type="text" class="form-control" name="your_name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" name="email">
</div>
<div class="form-group">
<label for="title">Event title:</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="location">Event location:</label>
<input type="text" class="form-control" name="location">
</div>
Upvotes: 0
Reputation: 21638
Get rid of the jQuery and do it with CSS.
input.form-control:focus {
background-color: lightyellow;
}
<input type="text" class="form-control">
Upvotes: 3
Reputation: 100
You can use jQuery selector to addEventListener.
Add the following to the <head>
tag.
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
$('input.form-control').focus(function(e){
highlightInput(this);
});
Upvotes: 1