I needed to be able to apply a specific class to all my img tags that were linked to their original size images, so that the full size image would be displayed in a fancybox. This was necessary as the content providers were not too happy about having to add the class name to their anchor tags by hand. The following gets a collection of all the image tags “img” that are inside anchor tags “a” and adds the required class name to their class attribute.
if (document.URL.indexOf(“blog”)>0)
{
$(“a img”).parent().addClass(“single_image”);
document.getElementsByTagName(“a”)[0].single_image=”;
$(“a.backToTop”).removeClass(“single_image”);
$(“a.single_image”).fancybox({‘hideOnContentClick’: true});
}
1. As there were issues with the classname being added to images that were not supposed to support the fancybox, the if statement makes sure that the classname and script are only applied to blogposts.
2. $(“a img”).parent() gets the collection of anchor tags. $(“a img”) gets the collection of image tags.
3. .addClass(className) adds the className to the class attribute of the anchors. This happens for all the anchors selected in the previous line.
4. document.getElementsByTagName(“a”)[0].single_image=”; this should be exactly the same as having said $(“a”)[0].removeClass(“single_image”); but for some reason, I couldn’t get that to work. Hence, pure javascript was used to remove the className from the first anchor in the collection. This was necessary as the first anchor was the logo and it was not supposed to be displayed in a fancybox (but, rather, navigate to the homepage)
5. $(“a.backToTop”).removeClass(“single_image”); as above, it was necessary to remove the className from the anchor tag that navigates the user to the top of the page.
6. $(“a.single_image”).fancybox({‘hideOnContentClick’: true}); this attaches the fancybox script to all tags that bear the single_image tag.
The lightbox/fancybox used can be found here.