Reputation: 229
I am fairly new to jQuery and teaching my self. Below you will see the code I am working on and an included JSFiddle.
What I am looking to do is add a class when I focus on an input/select and also have the class added when I click on the parent div. I basically have it working but in 2 separate functions.
Issues:
Possible solutions:
Please explain the code so I can learn from this. If you do not have a solution any hints or direction would also be helpful. Thanks in advance!
HTML
<div class="panel">
<input type="text"/>
</div>
<div class="panel">
<input type="text"/>
</div>
<div class="panel">
<input type="text"/>
</div>
CSS
.panel{
padding:15px;
background:grey;
margin-bottom:15px;
}
.panel-primary{
margin:0 15px 0 15px;
background:blue;
margin-bottom:15px;
}
jQuery
$(document).ready(function () {
$('.panel').click(function () {
$('.panel').removeClass('panel-primary');
$(this).addClass('panel-primary');
});
$('input, select').bind('focus blur', function () {
$(this).closest(".panel").toggleClass('panel-primary');
});
});
Upvotes: 0
Views: 129
Reputation: 7878
You can try something like this:
$('input, select').bind('focus blur', function (event) {
event.stopPropagation();
$('.panel').removeClass('panel-primary');
$(this).closest(".panel").addClass('panel-primary');
});
for your second function.
With .stopPropagation() you prevent the click event to "bubble" up the DOM. So it now never reaches the parent div to trigger your first function.
Upvotes: 2