I have been working on the Jenn Louise product pages this week which originally used an image zoom script by Ben Watts called Enhance Gallery, as the site was originally based off the default radiance theme from Shopify. I like script but it does not support touch based events and it can be quite jumpy when used with a mouse. I went searching for an alternative and found a commercial plugin called Cloud Zoom that I really like, as it offers great touch support and has an excellent smoothing algorithm. When I first tried it out it unfortunately it didn’t initially support Twitter Bootstrap or responsive designs, both of which are used on the site. I emailed their support team and to their credit they fixed both issues within a day, however in the meantime I had a look at adding these features to the open source Enhance Gallery. It turned out to be quite easy and interesting.
I started with the smoothing algorithm found in this excellent solution on stackoverflow – where would I be without stackoverflow! With some minor modifications including adjusting the frame rate to 60 frames per second and correspondingly adjusting the smoothing factor it was looking promising. The basic algorithm is to find the difference between the desired and current location, then add the difference divided by a factor on each frame. It’s basically an exponential decay function, which gives a nice smooth effect that slows as it approaches the destination.
While I was at it I also added a border region so that to see the edge of the image the mouse or touch just has to be in the border region, not on the edge of the zoom box. I also noticed that there is an issue with an overflow issue if the mouse stayed in the same position for a while. The decay function would still keep working, never reaching the desired position, until eventually the floating point number would overflow. The addition of Math.round solves this.
The second item was to add support for touch events, such that an iPhone, iPad or Android device could zoom the window without having to invoke the hover handler by tapping the image first. It turns out to be quite simple, with the mouseenter and mouseleave events replaced with touchstart and touchend, and the mousemove replaced by touchmove. This article by Deven Olsen is a great start for working with the touchmove event, leaving only one other major change – the inverting of the movement. Touch devices behave differently to the mouse in that we expect the content under the finger to follow as it is dragged, requiring a minor change to the algorithm to both invert the input and to increase responsiveness by reducing the smoothing function.
My fork of the code is up on Github and you can see it in action here. A Shopify user of the radiance theme can simply copy over their enhance.jquery.js file to use. All of the additions are customisable by passing in a settings object on start up.