jmhobbs

PanoramAh: Version Two

Last week I put together a quick script to display a panorama I took in Colorado.

It was a one-off script and I didn't think much of it until Naina Redhu left a comment asking about using it for multiple panorama's.

Well, why not?

It didn't take much to tweak it into a full fledged jQuery plugin. I just took the bit that made the panorama and tweaked it to use local references. While I was at it I removed the requirement for a pre-loader image in the markup. Have a look.

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

Using it is pretty easy too, just set up your HTML like so:

Loading...

Then make a collection and call panoramah() on it:

$( '.panorama' ).panoramah();

There's a demo available here and you can keep up with any changes at Github.