An image of a little cat! Isn’t he cute? Watch his sweet little eyes! Awwh! Miaow?
A sexy little effect I’ve always wanted is for the captions on my images to be laid adorably on top of them with the image showing through. Fair enough, I could achieve this with CSS and classes alone, but the idea of manually modifying every single bloody image somehow didn’t appeal to me that much. What did I do? Well, decided to be the lazy bastard I am and add in a little JavaScript.
I’m a total beginner with (even ‘lightweight’) programming languages, therefore the actual code is probably a little more bloated than need be. However, it’s still pretty small: the uncompressed file weighs in @ 7.53kb and will be even lighter if you do server-side compression. I’ve always liked the idea of compression. I always think of it like squeezing the juice out of a freshly picked orange, or the coffee being forced out when it separates. Yeah, anyway…
Now, I assume you’ve used the following code to display your image:
<!-- Begin image holder. Of course, these comments are optional -->
<div class="imgholder">
<img src="/images/the_orange_coffee.jpeg" mce_src="/images/the_orange_coffee.jpeg" alt="A cup of coffee with a slice of orange stuck on top, like an umbrella." />
<p>You've got to love the ingenuity of some people...</p>
</div>
<!-- End image holder. If you hadn't figured that out. -->
A Siberian Huskey with two different-colored eyes. That is his only purpose. Do not waste it.
The JavaScript works by scanning your page for divs with a class of imgholder and sticking them in an array. Arrays are like one of those big album cases which you stick all your discs in. This is actually an unhelpful analogy for me, because my discs end up everywhere. It’s really damned annoying. You try searching for that KT Tunstall album amongst piles of bootable CDs, copies of video games, the drivers that came with various graphics cards and the TimeSplitter games (simply amazing, by the way.)
Look what happened to your boss! He’s angry with you. Run!
Back onto topic, the JavaScript then takes each of these discs out and plays it, because it thinks you have great music taste. Right. It then gets out a pack of CD labels and either sticks evencaption.png or oddcaption.png on the album, obviously depending on its order on the page. These are transparent labels, though, so you can still see the original artwork beneath.
Dropping the fairly weak analogy, the caption (the paragraph appearing below the image in the code) is then pulled up on top of your image. You may be wondering what happens when your caption happens to be massive and the image, well, not so. Luckily, I actually have a brain too, and had the amazing idea that if the caption is more than half the image’s height, it isn’t pulled up. Yay. Bet you didn’t see that one coming, huh.
document.getElementsBySelector() function.)