Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Tips on fixing jQuery lag?

I have two footer icons on a page, and I've set up jQuery to image swap the icons when the user hovers over each icon. I've got this set up at the end of the page just before the closing body tag.

<script>
$('.twitter-icon').on({
  'mouseover' : function() {
    $(this).attr('src','images/twitter-blue_on.png');
  },
  'mouseout' : function() {
    $(this).attr('src','images/twitter-black_off.png');
  }
});
$('.treehouse-icon').on({
  'mouseover' : function() {
    $(this).attr('src','images/treehouse-green_on.png');
  },
  'mouseout' : function() {
    $(this).attr('src','images/treehouse-black_off.png');
  }
});
</script>

This works fine when I preview it, but once I actually made the site live, there is a noticeable time delay of about 1/2 second before the image swaps. Though after that first lag is out of the way they will swap instantly.

So I'm thinking there might be someone who knows how to get rid of that initial delay? It really bugs me! lol

1 Answer

Rather than swapping the image itself, try creating an image sprite that contains both versions of the image (resting and hover state). Then set up your hover so it only has to move the positioning of the background image to the hover state. More info here

Jeff Lemay
Jeff Lemay
14,268 Points

I second this. You should definitely use css for hover effects, whether you use an image sprite like Dan suggested or two separate images.

With an image sprite, you have your default and hover images on the same image/canvas. Then you set the background position to top for one and bottom for the other:

.icon-sprite {
   background-position: center bottom;
}
.icon-sprite:hover {
   background-position: center top;
}

Thanks guys, I'm gonna try that out. I've used this (below) cross fade before but never sprites...

#cf {
  position:relative;
  height:281px;
  width:450px;
  margin:0 auto;
}

#cf img {
  position:absolute;
  left:0;
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

#cf img.top:hover {
  opacity:0;
}