Creating a Caption Slider with jQuery

Posted on by

I know I’ve been on a jQuery kick. I guess I’ve been doing a lot of user-interface coding lately. I really enjoy using jQuery. It really makes a developer’s life easier as it handles most cross-browser problems. Also, the way you write it just seems to make logical sense to me.

Anyway, here’s what I’ll be creating today… (go ahead and mouse over Jack).

Hello, my name is Jack

No need for an independent sample page. This script is pretty easy. It’s really just a few lines of JavaScript/jQuery.

English Translation:

Starting with the HTML, I use a DIV with a class of “theBox” as my main container. I used a class and not an ID intentionally, so it gives me the option to add another image with a caption on the same page (thinking ahead is always good programming practice). The CSS is pretty standard. The important part is to have a position of relative and overflow:hidden on “theBox”. Then, when you set a position:relative for “theBoxCaption”, you need to set the “top” property to match the height of “theBox”. The rest is really powered by jQuery. I’ve seen a lot of plugins out there and always wanted to come up with a way to do this on my own.

The only property I’m animating here is the “top” property on “theBoxCaption”. Initially, this gets set by the CSS of the page (it’s set to 200px). Then, I do some calculating to find out what the top value needs to be at the end of the animation. I subtract the height of the “captionBox” from the height of “theBox”. Then, it’s just a matter of sending that value in an animate function. The second argument of my .hover() function is actually the mouseOut event. A lot of people don’t realize that you don’t need a separate MouseOut event and that you simply just write that in the 2nd argument for the .hover() function. For this example, I’m just reversing what I did and animating the “top” value of “theCaptionBox” back to the height of the main parent container (“theBox”).

This has sort of encouraged me to write my own plugin – maybe I’ll repost this topic at that time. I hope you find this useful.

PixelBind is a website company that was founded in July of 2011 in Myrtle Beach, South Carolina. We are proud to say that we’re here to make the web a better place. We strongly believe that a website is your first impression to the world, and it should be a good one; one that someone should remember, because the world is full of competition. PixelBind ensures that you’re remembered by presenting your audience a damn good website.