31 July 2012

Image Description Overlay using JavaScript and jQuery

Handwritten by TVD

We all know accessibility and SEO are important facets of web application development. Accessibility, itself, speaks to the heart of what the web is all about. Namely, the ability for people to break free from whatever bonds hold them at bay and explore a world vast and wild. I know first hand the power of that freedom.

While writing this article, I got to see live and in-person how magnificent the Ferrari California truly is. Inspired and pumped, I implemented one of its dashboard gauges. You can find the Ferrari California dashboard gauge in our JavaScript Gauge Suite.

SEO and Accessibility Matter

Accessibility and SEO come into play particularly with image rich applications. Think Instagram for example. With these types of applications, it is important to specify the alt attribute on each and every image:

<imgclass="overlay"src="ferrari.jpg"alt="The Ferrari California is a grand touring sports car. The car revives the 'California' name used for the late-1950s Ferrari 250 GT."/>

This ensures the application is readable to a whole host of folks who otherwise wouldn’t be privy to the information. Wouldn’t it be cool if we could reuse that alt attribute to enhance our application? That’s exactly what we are going to do in this lesson — JavaScript style.

Adding Image Overlays (Automatically)

The image must have an overlay class attribute. Then we’ll write code to reuse each image’s alt tag to create a description overlay on hover.

Here is the jQuery and JavaScript code to add the image overlay:

$(window).load(function(){$("img.overlay").each(function(){//Wrap the image with an overlay$(this).wrap("<div class='description_overlay'></div>");

//Append the description to the overlayo.append("<div class='description'><div class='description_content'></div></div>");

//Align the description with the imageo.find(".description").css("opacity",0);o.find(".description").css("width",$(this).width());o.find(".description").css("display","block");o.find(".description").css("text-align","center");

//Set the description from the img alt attributeo.find(".description_content").html($(this).attr("alt"));