Reputation: 4660
I have a structure like this:
<div id="parent">
<div class="children">Child 1</div>
<div class="children">Child 2</div>
<div class="children">Child 3</div>
<div class="children">Child 4</div>
</div>
In jQuery, I want it so that when you hover over anywhere on "parent" (including "children"), "parent" gets a white border around it. Here is what I currently have:
$("div#parent").hover(function(){
$(this).css("border-color", "white");
});
$("div#parent").mouseOut(function(){
$(this).css("border-color", "black");
});
The problem with this code is that if you mouseout over the child, it often does not become black again. Also, because of the children, it sometimes seems not to fire the hover.
I would like this to work very cleanly and simply without error. What can be done?
Thank you for your help! :)
Upvotes: 1
Views: 192
Reputation: 3965
Try this:
$(function(){
$('#parent').mouseover(function(){
$(this).css("border-color", "white");
}).mouseout(function(){
$(this).css("border-color", "black");
});
});
Upvotes: 0
Reputation: 4399
Try this:
$("#parent").hover(function(){
$(this).css("border-color", "white");
});
$("#parent").on('mouseleave', function(){
$(this).css("border-color", "black");
});
Upvotes: 3
Reputation: 388316
hover() registers both mouseenter and mouseleave handlers, so you can pass two event handler functions to .hover()
first one for mouseenter
and second for mouseleave
and remove the mouseout handler
$("#parent").hover(function(){
$(this).css("border-color", "white");
},function(){
$(this).css("border-color", "black");
});
Demo: Fiddle
Upvotes: 6