PanoramAh: A jQuery Panorama Viewer

Update (2010-08-25)

New version that supports multiple panorama's on a page, check it out here.

As I have recently made some panoramas with Hugin I needed a solution for displaying them on the web. I searched around a bit and found this one from Gaya Designs.

I liked the clever technique for scrolling linked to the mouse via the background-position, but I didn't care for the Prototype dependency or the rather large and feature-full script.

Taking that into consideration I whipped up my own viewer based on the same principles that used jQuery.

The Markup

The markup is dead simple. A class to identify the container, a little loading message and an img tag to preload into. I used the rel attribute on the container to carry the image URL and the width of the image. Height of the container should be set to the height of the panorama, width can be anything you like.


The JavaScript

Again, pretty super easy. I'll let the code speak for itself.

var PanoramAh = {
  init: function () {
    // Get the element
    el = $( ".panorama" );
    // Extract the relevant data from the rel attribute
    panorama_width = el.attr( 'rel' ).split( ':' )[0];
    panorama_url = el.attr( 'rel' ).split( ':' )[1];
    // Get the preloader
    img = el.find( '.preload' )
    // Setup the onload callback
      function () {
        // Set the background to the image
        el.css( 'background', "transparent url( '" + panorama_url + "' ) no-repeat" );
        // Clear out the loading crap
        el.html( "" );
        // Set up the mouse monitoring
          function ( event ) {
            // Get the offset
            offset = Math.floor( ( panorama_width - el.width() ) * ( ( event.pageX - el.offset().left ) / el.width() ) )
            // Mind the overflows
            if( offset <= panorama_width - el.width() ) { el.css( 'background-position',  '-' + offset + 'px 50%' ); }
    // Start the loading process
    img.attr( 'src', panorama_url );

The Demo

It works for me in Firefox and Chrome. YMMV.

Check it out!