Search code examples
jquerymouseovermouseout

Simple jquery caption not working


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>

Solution

  • 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);
    });