The problem is that when the caption appears, your mouse is no longer on the image - a mouseleave
event is sent to the image and a mouseenter
to the caption div. The former triggers the fadeout. You can solve that by placing both the image and the caption into a container element (e.g. a <div>
) and applying the event handler on this container. Then no matter whether the caption is showing or not, the outer container will not receive a mouseleave
.
EDIT: Here's a working example:
HTML:
<div class="captions" id="talktostrangers">
<ul>
<li>
<img src="image1.jpg">
<div class="caption">Caption 1</div>
</li>
<li>
<img src="image2.jpg">
<div class="caption">Caption 2</div>
</li>
</ul>
</div>
Javascript:
$('.captions li').hover(function() {
$('.caption', this).fadeIn();
}, function() {
$('.caption', this).fadeOut();
});