Blogger: How to get the images in listings to link back to the post

Images in Blogger posts, by default, are wrapped by an anchor. This anchor will either open the image in a new window, or open a lightbox with the image (either you have this setting activated or not). This is the standard behavior in the post page or in the posts listing page.

Usability wise this is pretty crappy. Users expect the image to link back to the page it refers to in a list of articles. You don’t want to get your users angry because your site doesn't work as they expect.

Here’s what you have to do to make the image link to the post.

Include this code in the <head> section of your post, or if you have a dedicated scripts file you can place the linkListImagesToPosts() function there. You can host your script on your Google Drive account.

The call to the function should still be in the head, because we only want to target the index pages, and we can only use conditions in the template file (line 2).

 <script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'/> 
 <b:if cond='data:blog.pageType == &quot;index&quot;'> 
 <script  type='text/javascript'> 
 //<![CDATA[ 
    function linkListImagesToPosts() { 
         $(".blog-posts .post-outer").each(function(index) { 
                 // get the post url from the title anchor 
                 var newhref = $(this).find("h3.post-title a").attr("href"); 
                  
                 // find the image anchor and clone it 
                 var a = $(this).find("img").first().parent("a"); 
                 var aclone = a.clone();         
                  
                 // change the link in the image anchor 
                 aclone.attr("href", newhref); 
                  
                 // replace the old anchor with the new one 
                 a.replaceWith(aclone); 
         }); 
    } 
    $(document).ready(function() {                 
         linkListImagesToPosts(); 
    }); 
 //]]> 
 </script> 
 </b:if>

The linkListImagesToPosts() is very simple, we loop through all the posts, and for each post we strip the URL from the title anchor and we’ll copy that URL into the image anchor.

clone() usage

There’s a problem with simply replacing the href value in the image anchor. If the blog is using lightbox, its scripts will attach an event to the anchor that will prevent the anchor from triggering the href redirect.

So even if you’re able to change the href, the anchor will still show the lightbox when you click it.

We solve this problem by using jQuery clone() function. The copy object will not carry the attached events, so all we need to do is change the href in this object and replace the original anchor with its clone.

Dércia Silva
Posted by Dércia Silva on December 19, 2013

Related articles