Placed in: Home arrow Programming arrow Webdesign arrow Creating a polaroid photo viewer with CSS3 and jQuery
Creating a polaroid photo viewer with CSS3 and jQuery

Italy. A beautiful country that my girlfriend and me visited last year during our summer holiday. While we were there, we took a lot of pictures that would look pretty nice on polaroid.

Placing them on simple polaroids on a webpage simply didn't do it for me. I wanted to drag them around, rotate them and still have a fun time. That's were CSS and jQuery come in play. By combining the CSS3 Box Shadow and Rotate properties, this effect is relatively easy to create. When dragging a polaroid around, you'll see the shadow. When it's placed down, it's rotated to the left or the right (random).

Polaroid Photo Viewer with CSS3 and jQuery

This example is making use of CSS3 and jQuery, just to show the effect when combining two powerful techniques. The CSS3 is injected by jQuery, keeping the CSS file clean.

Demo polaroid photo viewer with CSS3 and jQuery   Download polaroid photo viewer with CSS3 and jQuery

IMPORTANT NOTE:
Sadly, CSS3 and HTML5 aren't the standards (yet) these days (when will it ever be?). Since this demo is using CSS3, not all modern browsers will be able to show off the full effect. Because of this, it only works on Apples Safari and Google Chrome as they are the only browsers supporting the Transform and Box-Shadow property of CSS3 via the -webkit- prefix. Mozillas Firefox 3.1 is getting these properties too (with the -moz- prefix). So, for now, this is just for fun - Other browsers will display the polaroids, but won't have the neat shadow while dragging and rotating while placing them down.

With that said, check out how you can re-create this effect and learn some more about CSS3 and jQuery. Check out one of my older articles if you're searching for an image gallery that isn't using CSS3.

Just for the record: Not all pictures were taken by me (just some of them). Most of them were from stock.xchng.

Safari Demo

Check out this small video I placed on YouTube, showing this effect in full glory (rotating and adding a shadow while dragging).

HTML

The HTML of this page isn't really hard to understand.

 
<div class="polaroid">
  <img src="images/01_colosseum.png" alt="Colloseum" />
  <p>Coloseum in Rome</p>
 
</div>
<div class="polaroid">
  <img src="images/02_vatican.png" alt="Vatican" />
  <p>Vatican</p>
</div>
<!-- More images here -->

The polaroid-class is the container of the polaroid. The next element (img) is the picture, the element after that (p) is used for the caption below the image. Repeat this as many times as you want with all your polaroids!

CSS

Just like the HTML, the CSS part of this example is pretty simple.

 
.polaroid { width:368px; height:376px; background-image:url(../images/polaroid-bg.png); position:absolute; }
.polaroid img { width:335px; height:275px; margin:25px 0 0 15px; }
.polaroid p { text-align:center; font-family:Georgia,serif; font-size:20px; color:#2E2E2E; margin-top:15px; }

Note that polaroid-class has a fixed width and height (Same size of the background image). It's also placed on an absolute position. The img of the polaroid has also been moved to a fixed position. The caption is aligned to the center.

jQuery and CSS3

Now for the real fun! The HTML and CS weren't so interesting, now this is going to be. I'll split the code in several parts and make sure you read the comments in the code.

 
google.load("jquery", "1.3.1");
google.load("jqueryui", "1.7.0");

I'm using Googles JavaScript Libraries API to load jQuery and the jQuery UI. We're going to need the last one for the jQuery UI Draggable Component for dragging the polaroid around.

 
   // Set the Z-Index (used to display images on top while dragging)
   var zindexnr = 1;
   
   // boolean to check if the user is dragging
   var dragging = false;
   
   // Show the polaroid on top when clicked on
   $(".polaroid").mouseup(function(e){
      if(!dragging) {
         // Bring polaroid to the foreground
         zindexnr++;
         var cssObj = { 'z-index' : zindexnr,
         '-webkit-transform' : 'rotate(0deg)' };
         $(this).css(cssObj);
      }
   });

The zindexnr variable is used to "remember" the z-index. Every time a polaroid is clicked, the z-index is added by one, making the polaroid come to the foreground. The dragging boolean is to determine if the user is dragging the polaroid, or just clicking on it. When clicked (like in this part of the code), the polaroid is rotated to it's original position (zero degrees) and placed on top.

I actually made this method to "zoom in" to the polaroid, but removed it later on. If you still want to zoom in, simply add your code in that function.

 
   // Function to get random number upto m
   // http://roshanbh.com.np/2008/09/get-random-number-range-two-numbers-javascript.html
   function randomXToY(minVal,maxVal,floatVal) {
      var randVal = minVal+(Math.random()*(maxVal-minVal));
      return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
   }

The function that you see above is to generate a random number between two integers. I added the source URL where I got the function from; We'll need it in the next part of the code:

 
   // Make the polaroid draggable & display a shadow when dragging
   $(".polaroid").draggable({
      cursor: 'crosshair',
      start: function(event, ui) {
         dragging = true;
         zindexnr++;
         var cssObj = { '-webkit-box-shadow' : '#888 5px 10px 10px',
            'margin-left' : '-10px',
            'margin-top' : '-10px',
            'z-index' : zindexnr };
         $(this).css(cssObj);
      },
      stop: function(event, ui) {
         var tempVal = Math.round(Math.random());
         if(tempVal == 1) {
            var rotDegrees = randomXToY(330, 360); // rotate left
         } else {
            var rotDegrees = randomXToY(0, 30); // rotate right
         }
         var cssObj = { '-webkit-box-shadow' : '',
            '-webkit-transform' : 'rotate('+ rotDegrees +'deg)',
            'margin-left' : '0px',
            'margin-top' : '0px' };
         $(this).css(cssObj);
         dragging = false;
      }
   });

Let's break this up a little bit.

  • $(".polaroid").draggable( - Needed for jQuery UI to make the element draggable.
  • start: function(event, ui) - This is called when the user starts dragging and the shadow is needed.
  • '-webkit-box-shadow' : '#888 5px 10px 10px' - Added to inject the CSS3 "box-shadow" property.
  • $(this).css(cssObj); - Adding the CSS to this, which is the polaroid.
  • stop: function(event, ui) - This is called when the user stops dragging and the shadow is removed, including a rotation.
  • var tempVal = Math.round(Math.random()); - Generating a random number (1 or 0), needed to rotate the polaroid left or right.
  • var rotDegrees = randomXToY(330, 360); - Generating a random number between 330 and 360 to rotate the polaroid to the left.
  • var rotDegrees = randomXToY(0, 30); - Generating a random number between 0 and 30 to rotate the polaroid to the right.
  • '-webkit-box-shadow' : '' - Removing the shadow.
  • '-webkit-transform' : 'rotate('+ rotDegrees +'deg)' - Rotating the polaroid based on the randomly generated degrees.

That's about it! I also added a function that randomly scatters the polaroids when everything had loaded and tadaa: An awesome polaroid photo viewer with CSS3 and jQuery.

Conclusion and Download

Hopefully CSS3 will become the standard quick and users will kick out the old browsers too. This way, this technique would be pretty awesome to be used to display some crazy photo galleries. It's relatively simple to achieve, still the effect is pretty powerful. It's really fun too!

Demo polaroid photo viewer with CSS3 and jQuery   Download polaroid photo viewer with CSS3 and jQuery

I hoped you learned something today about CSS3 and/or about jQuery. Do you think this could be useful somewhere or that you're going to use it in the future? Or do you want to improve the code by adding the zooming functionality when the user clicks on the image? Please share!

UPDATE

For those people that are interested in a non-full screen version of this script, I just released it too.


Tags:  polaroid photo viewer css3 jquery tutorial webdevelopment

Interested in this topic? You might enjoy another article I've written called

Did you like this article? Subscribe to my feed or email to keep updated on new articles.

Spread the word and submit to:
Digg!Reddit!Del.icio.us!Facebook!Technorati!StumbleUpon!Newsvine!Furl!Ma.gnolia!
Comments
Add NewSearchRSS
Gaya - nice   2009-03-16 21:38:13
Gravatar image Looks good Marco =D, really nice use of Javascript.

I hate the fact that not all browsers are implementing the rules, making it almost useless to put on your website as a nice rich application.
Damn the browsers. It would be so easy for us if there was 1 good standard which HAD to be implemented, or else the browser wouldn't be allowed online.
We can only dream.
Marco - Thanks Gaya!   2009-03-16 21:45:03
Gravatar image Thanks for the reply mate!

Also check the JavaScript file in the demo and search for the following:
Quote:
// Internet Explorer doesn't have the "window.innerWidth" and
"window.innerHeight" properties

I'm really sorry for that mega-ugly "fix", but IE only allows checking the browser width & height after the BODY tag.

Damn you Microsoft!
Remco - Opera   2009-03-17 00:11:05
Gravatar image Works like a charm in Opera 9.6x of course :)
Marco - Thanks! Didn't know   2009-03-17 07:16:41
Gravatar image Hi Remco,

Thanks for checking it with Opera - Didn't test that browser. Didn't expect to "not work" in that one ;) .

I do have one question:
Is it because I added the "box-shadow" (plain) CSS3 property in the JavaScript file, or is it because of the "-webkit-" prefix (which means that Opera is using the Webkit engine too)?
Vladimir - Click   2009-03-17 09:23:46
Gravatar image very good, but they are not clickable :(
Marco - They are!   2009-03-17 13:32:21
Gravatar image Actually, they are. Check the article and read the JavaScript examples from
Quote:
$(".polaroid";).mouseup(function(e){

Currently, "zooming in" isn't added, but can be if you just modify that function ;). Now, when you click a polaroid, it just rotates back to zero degrees and placed on top :) .
Hezi - Kudos!   2009-03-17 09:43:10
Gravatar image very very nice!

Remco - you rock!
Marco - Remco? Marco?   2009-03-17 13:45:33
Gravatar image Thanks for the compliment Hezi ;) ! I assume that you complemented me (my name is Marco)? Or did you compliment Remco for testing in Opera?
Janko - Bravo!   2009-03-17 13:28:12
Gravatar image Awesome example, Marco. Good idea to make an example video.
Marco - Thanks!   2009-03-17 13:33:52
Gravatar image Thanks Janko! Yeah - The example vid is for IE and FF users (FF will have to wait a while, IE even longer).

Like you said in the email: You could also retrieve your FlickR API using JSON to fill in the polaroids using your FlickR images ;) !
Tom Sinclair   2009-03-18 16:15:05
Gravatar image Great tutorial :) Will definitely have a play around with this later!
ben smithson - Wicked Awesome   2009-03-19 01:59:21
Gravatar image This is gah-hhhreat! Loving the drag n drop images.
Thanks for a great post!
Will B. - How do you rotate?   2009-03-30 21:56:20
Gravatar image Didn't quite figure out how to rotate the images, though.
Marco - CSS Transform   2009-03-30 22:23:59
Gravatar image The CSS "transform" property allows you to rotate elements.
Quote:
img { '-webkit-transform' : 'rotate(100deg)' }

This will rotate all images with 100 degrees. This only works for browsers supporting the -webkit- prefix (Safari & Chrome).

Hope this helps!
not2comply   2009-03-31 10:08:59
Gravatar image Eventhough CSS3 isn't fully supported by some browser, I found myself unable to stop playing with CSS3.

And this one is totally Awesome...

Great Work. and thanks for sharing.
Marco - Thanks!   2009-03-31 16:56:00
Gravatar image The same counts for me - CSS3 has way to many awesome feautures to be put to the side.

Hopefully that CSS3 will be the standard "soon" so Flash website will be completely obsolete and codes will have more ease in creating fancy stuff on a website.

Thanks for your comment!
Anthony - Thank You!   2009-03-31 21:01:25
Gravatar image This is one of the best JavaScript examples I have ever seen.

Thanks
stack - Shadoooows   2009-04-02 17:45:49
Gravatar image for a better shadow, stack transparent layer and for each moveto x+10 and y+10 !
know what i mean ?
Marco   2009-04-02 18:19:10
Gravatar image Yeah - you're right. You could append another div with a transparent background image that would move to x+10 and y+10. This solution will make it cross-browser compatible.

But that wasn't where this article was aiming to - It was about the awesomeness of CSS3 and what you can do with it ;) . That's why I choose the CSS3 box-shadow property.

Anyway, thanks for your input - Always appreciated!
Henry - I like it   2009-04-02 21:08:29
Gravatar image Really I like it. Congratulations.
Cyrus - Fixed bg needed   2009-04-05 11:08:14
Gravatar image The ui is nice. Can anyone help me out how to fix the width and height up to which a specific picture is expandable.

I tried using background:no-repeat. but didn't seem to work for me.

Thanks.
Marco - What?   2009-04-05 21:11:58
Gravatar image Hi Cyrus,

Thank you for your comment.

What do you mean with "specific picture is expandable"?

If you can't explain it in the comments, please contact me so we can discuss this further.
Cyrus - Background fixed   2009-04-12 16:38:12
Gravatar image Background was fixed by adding this two property to polaroid draggable

containment: '#containment-wrapper',
scroll: false,

Thanks.
Cody - Flickr   2009-04-14 04:45:45
Gravatar image Will there be a version with flickr integrated into it?
Marco - Could be!   2009-04-16 07:43:22
Gravatar image Hi Cody,

Thanks for your comment.

I don't know if there will be a FlickR version, but thanks for the idea. Just keep on checking this website for more updates and I might give it a shot!

Greetings,,
Blog Seo - En explorer 8 si funciona   2009-04-20 12:09:55
Gravatar image :woohoo: Increible, pero en Explorer 8 si que funciona la galeria..

Gracias por el aporte ...

Saludos

Dbarrera
Tran Ngoc Hieu - Blue Sky   2009-05-06 08:50:10
Gravatar image See very beautyful
very cool
thank
Pawan   2009-05-12 12:07:05
Gravatar image :angry:

Firefox 3 ... "The best web browser .. lol " ... does not gives scroll bars also when running this example.. IE atleast provide the scroll bars..
Pawan   2009-05-12 12:08:18
Gravatar image :)
but.. ya.. amazing example... and that should be the point of discussion...
thanks
Tom - No Fullscreen   2009-06-04 18:33:51
Gravatar image Very nice script, compliment! But, is it somehow possible to reduce it into a div and not to have it allways fullscreen?
Josh   2009-08-07 22:38:32
Gravatar image I want to know the same thing.
JAMES Gray - In div container   2009-08-11 05:40:48
Gravatar image Hi - Great script - I'm also trying to container the gallery in a div - has anyone worked a solution?
Marco - Working on it   2009-08-12 01:51:30
Gravatar image Hi people,

Thanks for the comments. I'm currently working on a version "inside" a div-container. Simply keep an eye on the homepage of Marcofolio, since it'll be released there.

Greetings,,
Marco - Done!   2009-08-12 16:14:52
Gravatar image Done!

The new script has been placed online.

Good luck with that folks!
James Gray - THANKS MARCO!   2009-08-13 02:34:58
Gravatar image Thank you so much Marco - where do we donate!
Marco - No problem!   2009-08-13 06:01:59
Gravatar image No problem - glad I could help some people out.

You don't need to donate - simply visit Marcofolio.net a couple of times / leave some comments and feedback, that's all I need.
robb   2009-07-18 22:05:54
Gravatar image nice tutorial.
thx for sharing
martin - thank you   2009-07-27 17:52:34
Gravatar image thank you for sharing. i like this tutorial and the effects are great!
good work!
Efe - Thanx   2009-08-01 13:07:43
Gravatar image thanx , good work!
Arrow - Permision   2009-08-10 17:29:19
Gravatar image May I use this script in comertial project?
What caind of license this script is?
Marco - Yes, but..   2009-08-11 02:07:47
Gravatar image Everything that is released on Marcofolio.net is released under a CC3.0 license. This means you can use this work when and where-ever you want it, as long as you tell who the original author was (Marcofolio.net).
Arrow - permission - cd   2009-08-11 12:29:42
Gravatar image nice:P but what will be when I will change some code? (css, html, another design??)
Is it no problem when I still leave message in css, javascript file that Marcofolio.net is original author??
Marco - Correct   2009-08-12 01:50:46
Gravatar image Yup - you're correct. Simply leave a message in the CSS/JS etc. that looks something like "original author.." and "modified by.."

Good luck!
Ytrog - Nice   2009-08-12 12:22:22
Gravatar image Nice app.

I'm not sure though that a Creative Commons licence is the best choice for software. From what I understand it is more or less meant for things like pictures or text. Wouldn't GPL or LGPL be more appropriate in this case?
Ytrog - Addition to last post   2009-08-12 12:23:44
Gravatar image I forgot to mention it works on Firefox 3.5 ;)
Arun V - Nice Work   2009-08-20 08:13:53
Gravatar image Hey Man, I Found your Works, Nice Works, Good..

Thanks

Arun
BCmoney - Adding new photos...   2009-09-16 03:00:43
Gravatar image I was able to add new photos to the DOM but it makes the polaroids undraggable. I first put all the polaroids in one parent "polaroids" div, then used the following simple DOM addition:

Code:

function addPolaroid(polaroidName,imageURL)
{
top.window.document.getElementById('polaroids').innerHTML+=""+polaroidName+"";
}


I think it's probably something to do with innerHTML putting HTML on the page but not actually into the DOM... maybe we need to use createElement + appendChild?

Will dig into the code more but just thought I'd check if you know offhand why adding one more polaroid renders every polaroid undraggable.

Thanks for a wicked JS image gallery!
selva comments - Comments - Good work..   2009-09-21 12:28:24
Gravatar image We liked it very much. We were looking for integrating the same in our website
bTop - Very nice.   2009-09-28 21:34:00
Gravatar image Hi, it's amazing! I like this. <img src=hock:' />
bTop - Very nice.   2009-09-28 21:34:49
Gravatar image <img src=hock:' /> Hi, it's amazing! I like this.
Lurker   2009-10-22 00:09:45
Gravatar image Works great in Safari. However this blog page doesn't. The text runs off the edge of the white area.
Read more...
Name:
Email:
  Gravatar enabled.
Website:
Title:
UBBCode:
[b] [i] [u] [url] [quote] [code] [img] 
 
 
:angry::0:confused::cheer:B):evil::silly::dry::lol::kiss::D:pinch:
:(:shock::X:side::):P:unsure::woohoo::huh::whistle:;):s
:!::?::idea::arrow:
 
Unsubscribe from e-mail notifications.
 
< Prev   Next >
Subscribe

If 3513 people are reading this site every day, why don't you?