How to Add Sliding Text on Images Using jQuery

jquery logo.png

I frequently get asked by my students how to add sliding text over images. In this lesson we will produce a very simple hover effect on an image which will result in text being shown.

You can see the before and after images below.

lionBefore.jpg
lionAfter.jpg

When we hover over the lion image the description will slide up.  When we exit the image the description will slide back down again.

STEP 1: The HTML

First, we will create the basic HTML structure.

Line 6: remember that you will need to include a reference to jQuery, either a local copy or from a CDN such as Google. 

Line 7: a link to our stylesheet.

Lines 10 - 16: the basic structure of the image and rollover content. The content div is inside the main rolloverContainer and will be partially hidden using css.

STEP 2: The CSS

This css should be fairly easy to follow. 

The rolloverContainer has relative positioning applied with overflow: hidden. This is how we are positioning and partially hiding the content div. 

Line 15: The content div has an absolute position.

Line 16: We move the content div 265 pixels from the top of the rolloverContainer div. You will need to adjust this number depending on your own image size.

STEP 3: The jQuery Code

We now add the jQuery code to our html page.

Line 9: we have declared a variable which will be used to position the content div when we hover over our image. In this case we want it to be 220px from the top.

Line 10: when we stop hovering we will position the content div 265 pixels from the top. Note that this number matches the value on line 16 of our css.

Line 14: this checks for a mouseenter over the rolloverContainer. If theis is true then we run a function

Line 15: we take the content div and animate it to 220px from the top of the rolloverContainer div.

Line 17: we detect a mouseleave and run a function.

Line 18: we reposition the content div back to its starting position.