[Drupal 7] How to load an image in colorbox using jQuery?

| | 2 min read

It is easy to show an image pop-up in Colorbox using Views in a Drupal website. You just have to change the image formatter in Views. However if you don't have a View and you still want to load the image in Colorbox, you can do it using jQuery. Read on to know how to load an image in Colorbox using jQuery in a Drupal 7 website.

Suppose you have an image inside the class 'product-img' and when you click on the image you need this image to be opened in Colorbox. Use the function given below to do this

$(".product-img img").click(function(){ 
   // spanId contains the id of the clicked image's parent div.This is helpful if there are more than one images.
   var spanId = jQuery(this).parent().attr("id");  
   // popup_content has the src value of clicked image.
   var popup_content =$('#'+spanId).html();
   // loads the image in colorbox.  
   $.colorbox({html:""+popup_content+""});          
  });

There may be other cases when you want to show another image while clicking( lets say the same image with a different image style). To do this you can pass the required path as argument to the jQuery function. For eg: the function below receives an image's path as the url.

jQuery(document).ready(function() {
    jQuery.testfun = function(test) { //test contains the path of the image
      var img = new Image();          
      img.src=test;
      img.onload = function() {
        var height = img.height; 
        var width  = img.width;
        jQuery.colorbox({html:"<img src='"+test+"' width='"+width+"' height = '"+height+"'/>"});
      }
    }   
  });

In case of image styles the images are created only when they are called by the browser. As jQuery may try to load the image, before it is created, the Colorbox will return an empty value. To solve this, you can wait for the image to load first. Its for this reason the code above is written inside img.onload = function() {}.