Search code examples
javascripthtmlmouseentermouseleave

Basic javascript mouseOver and mouseOut script being glitchy


I'm trying to make a basic javascript effect, where when you hover over a thumbnail, the thumbnail will fadeTo a .5 opacity, and an overlaying div will appear. I have the effect in place, but for some reason the script is buggy and the animation lags. Can someone explain to me why this is happening?

My script:

Html

<div class="thumbnailholder">
    <div class="thumbnaildesc">
            Lester Beall poster blah blah
    </div>
        <img class="thumbnail" src="img.jpg"/>
    </div>

Javascript

    <script>

$('.thumbnailholder')

.mouseenter(function () {
    $(this).find('.thumbnaildesc').fadeIn(400);
    $(this).find('img.thumbnail').fadeTo("fast", 0.5); })

.mouseleave(function () {
    $(this).find('.thumbnaildesc').stop(true).fadeOut(400);
    $(this).find('img.thumbnail').stop(true).fadeTo("fast", 1); })


</script>

Thanks!


Solution

  • Just animate the opacity, to prevent problems with fadeIn, fadeOut and fadeTo. These problems occur, because fadeOut results in a display: none, which does a little more then hiding. In fact, display: none disables further user interaction with the element and virtually removes it from the DOM. So things might get glitchy.

    Transitioning with .animate() (documentation):

    $('.thumbnailholder')
    .mouseenter(function() {
        $(this).find('.thumbnaildesc').animate({opacity: 1}, 400);
        $(this).find('img.thumbnail').animate({opacity: 0.5}, 400);
    })
    .mouseleave(function() {
        $(this).find('.thumbnaildesc').animate({opacity: 0}, 400);
        $(this).find('img.thumbnail').animate({opacity: 1}, 400);
    });
    

    Fiddle

    As Simon H mentioned: A pure CSS solution would more performant, especially, if you have a lot of thumbnails:

    .thumbnailholder {
        position: relative; 
    }
    .thumbnailholder img {
        opacity: 1;
        transition: opacity .4s ease-in-out;
    }
    .thumbnailholder:hover img {
        opacity: .5;
    }
    .thumbnailholder p {
        position: absolute;
        top: 0;
        opacity: 0;
    }
    .thumbnailholder:hover p {
        z-index: 100;
        opacity: 1;
        transition: opacity .4s ease-in-out;
    }
    

    Fiddle