I want to display a toolbar if the mouse is over a div or any of the div‘s nested elements. But the following solution with jQuery 1.7 only works if the mouse is over the div directly what is only possible if I add a padding to the item css class.
<head>
<script type="text/javascript" src="jquery-1.7.min.js"></script>
<style type="text/css">
.toolbar { display: none; }
.item { padding: 1px; } /* doesn't work without padding! */
</style>
<title>Demo</title>
</head>
<body>
<div class="section">
<div class="item">
<p class="toolbar">TOOLS</p>
<p>content</p>
</div>
<div class="item">
<p class="toolbar">TOOLS</p>
<p>content</p>
</div>
</div>
<script type="text/javascript">
$(".section").on(
"mouseenter",
".item",
function(event) {
$(event.target).children('.toolbar')
.show(100);
}
)
$(".section").on(
"mouseleave",
".item",
function(event) {
$(event.target).children('.toolbar').hide();
}
)
</script>
</body>
A padding of 1px wouldn’t be so bad, but it leads to bigger padding at the top and bottom and this workaround doesn’t work properly – especially if the mouse enters from the left or right side.
How can I handle mouseenter and mouseleave events without the padding trick?
It seems that the
event.targetis not the div – changing to$(this)fixes the problem -> http://api.jquery.com/event.target/http://jsfiddle.net/manseuk/StUvz/