2
\$\begingroup\$

I made a cool roll-over in CSS which displays an animated GIF when the parent is hovered.

Codepen

The problem is that I will have about 40 .day like that, all playing the animated GIF behind the circle at any time. I'm not sure that any browser/computer/connection can handle that much.

I tried to figure out a solution:

$( ".day" ).mouseenter(function() {
    $( ".play" ).append( "<img src="http://media.giphy.com/media/5Vb7xQB7Z3ScE/giphy.gif">" );
});

But I'm not sure if it will be better.

If someone as any idea to enhance that code, it would be really appreciated.

(The gif is just a sample.)

\$\endgroup\$
2
  • \$\begingroup\$ Could you please incorporate the entire demo in your question as a Stack Snippet? \$\endgroup\$ Commented Nov 19, 2014 at 11:24
  • \$\begingroup\$ When you say you have 40 .day elements, do you mean that they are all identical, or are they slightly different? (If different, could you give an idea of how they vary?) \$\endgroup\$ Commented Nov 19, 2014 at 11:26

1 Answer 1

1
\$\begingroup\$

First off, as far as I remember the gif is only loaded once regardless of how many there are on the page (Just opened the dev tools on that page and it does. Thank you crystal ball.) So HTTP request overhead isn't a problem.

As for rendering, slower machines and browsers will tend to crawl when rendering a lot of animated gifs. So 40 of those would considerably be a pain to do.

Now off to your code, yes it is a problem because you are you are getting all .play on every mouseenter, create and append a new image object for each of them. The overhead lies in the creating of a jQuery object for the .play set on each mouseenter as well as the generation of an image for each .play on each mouseenter.

I think the JS solution is better because it doesn't render 40 animated gifs all at once, and your code can be tweaked a bit for optimization. We can create the image just once and move it around using appendTo. Also, since the mouseover handler already has a reference to the target being hovered, we can use that as target for appendTo.

// Create an image just once
var img = $('<img src="http://media.giphy.com/media/5Vb7xQB7Z3ScE/giphy.gif">');

// Since we can't hover on .play because it's behind .img-circle, we designate
// .img-circle as our hover target, and use previousSibling to get the .play
$('.day').on('mouseover','.img-circle',function(event){

  // Here, we are not generating any new objects. img and this.previousSibling
  // are already provided for
  img.appendTo(this.previousSibling);
});

Here's a working demo

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.