Customising the Magnific Popup Lightbox in your Rails App

23 Sep 2013, by David Evans

For those not familiar with the term, a Lightbox is a javascript modal used to display previewed content front and centre.

Our Send A Script Rails App uses Lightboxes to show doctors' prescriptions sent from patients' iPhones to a pharmacy for pre-filling. These prescriptions can be tricky to read and can be sent from the iPhone upside-down when the photo is taken flat and the gyroscope loses its orientation.

What our Rails app needed was a Lightbox that allowed rotation of the doctor's prescription & expanded to fit the screen (responsive). I couldn't go past the stunning Magnific Popup, which had even been packaged in a gem for use with Rails' Asset Pipeline. The only thing missing was the ability to rotate images, so we built it. Here's how:

  1. Install the gem as per the GitHub documentation
  2. Apply the Javascript to the image element.
  3. Append a rotate button to the caption.
  4. Use the "open" callback to run javascript only when the Magnific Popup Lightbox is opened.
  5. Create a variable to store the angle of the image.
  6. Create a function to increment the variable by your desired angle & apply it to the image, upon clicking the rotate button.

$(document).ready(function() { // Begin Step 2
    zoom: {
      enabled: true,
      duration: 300
    image: {
      verticalFit: true,
      titleSrc: function(item) {
        var caption = item.el.attr('title');
        return caption + ' &middot; <input type="button" value="Rotate" class="rotate" />';  // Step 3
    },  // End Step 2

    callbacks: {
      open: function() { // Step 4
        newangle = 0;  // Begin Step 5

        $('.rotate').click(function() {

        function next() {
          newangle += 90;    
          if (newangle >= 360) newangle = 0;      
          return newangle;   // End Step 5

The result:

Cookies help us deliver our services. By using our services, you agree to our use of cookies.