This article will show you how to create pretty hover effects for your images using jQuery and CSS. The plan is to use a clean mark up, adding the necessary elements on the fly. What this means is that we are starting from barebones image HTML tags, with title attributes only. This can come useful especially if you already have hundreds of images that you want to apply this effect on.
View the Demo
Take a look at our markup:
Pretty clean right? Ok, now we start manipulating and styling with code:
Step 1: Wrapping Elements with jQuery
We are going to use jQuery to find all these images in a list item and check if it has a title attribute. If it does, it will wrap the image in a DIV with class name “wrapper”.
jQuery will also take the contents of the image’s title and place it inside another DIV called “caption” and place it inside wrapper, right after the image itself.
Now take a look at our mark up when the document loads:
Pretty slick right? Now let’s move forward.
Step 2: General Styling with CSS
Now that we have our DIVs in place, we can now set up the general styles with our stylesheet. What we’re trying to achieve is to hide the caption from a viewing area set on its containing DIV: wrapper.
Take a look at our stylesheet:
Note that the wrapper dimensions are taken from how wide and tall the images are.
Step 3: Events and More Styling with jQuery
Now back to our script, all we need to do now is assign a couple of events to the hover method of our wrapper DIV. Thankfully, jQuery’s .hover() simplifies this action by letting us bind two handlers (in and out) all within the same context.
All we need to achieve is a way to slide the caption DIV upwards or downwards when we hover (depending on the effect we want), and decrease the opacity. For the out, we put the caption in it’s original spot. Note that the demo has 3 effects: from the bottom, middle and top.
Notice that I also used the .animate() function for manipulating the CSS properties which renders all of our effects smoothly.
There you have it. You have just created your own image hover effects using jQuery and CSS.