Simple jquery caption not working

465 views Asked by At

I am trying to make a simple little caption box that fades in to 50% of the total width of the element when you mouseover the element, and stays there until you mouseout of the element.

It's working somewhat, but the problem is when I move my mouse over a link inside the .caption div, it's fading in and out (flashing), almost like it's treating the caption as a seperate element even though it's inside the main element. It also seems to randomly flash a couple times if I mouseout and mouseover quickly.

Here's my CSS:

.thumbs li {
    float: left;
    margin-right: 20px;
    width: 305px;
    height: 200px;
    position: relative;
    border: 1px solid red;
}
.thumbs li img {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 1;
}
.thumbs li .caption {
    position: absolute;
    width: 50%;
    height: 100%;;
    display: none;
    z-index: 2;
    text-align: center;
    color: #ffffff;
    background: rgba(0, 0, 0, .75);
}
.thumbs li .caption a {
    color: #ffffff;
}

Here's my jQuery:

$('.thumbs li').mouseover(function() {      
    $(this).find('.caption').fadeIn(500);
});

$('.thumbs li').mouseout(function() {       
    $(this).find('.caption').fadeOut(500);
});

Here's my HTML:

<ul class="thumbs">
<li>

    <img src="images/1.gif" alt="" />

    <div class="caption">

        <h4>Cycliner</h4>

        <p>
        <a href="#">Visit website</a>
        <br />
        <a href="#">View project</a>
        </p>

    </div>

</li>
</ul>
3

There are 3 answers

0
Mackelito On BEST ANSWER

You should use the mouseleave function instead of mouseout

http://jsfiddle.net/gygHg/

$('.thumbs li').mouseover(function() {      
$(this).find('.caption').fadeIn(500);
});

$('.thumbs li').mouseleave(function() {       
$(this).find('.caption').fadeOut(500);
});
2
Eirinn On
$('.thumbs li').mouseover(function()
{
    $(this).find('.caption').stop(false,true).fadeIn(400);
});
$('.thumbs li').mouseout(function()
{
    $(this).find('.caption').stop(false,true).fadeOut(400);
});

The stop will help your animation from flickering and persisting. I've made a jQuery plugin very similar to yours :)

0
cdeszaq On

Use mouseenter() and mouseleave() instead of the events you are binding to currently. Those trigger on the mouse entering the boundaries of the element they are attached to and won't re-trigger due to inner elements.

Here's an example