An Awesome CSS3 Lightbox Gallery with jQuery

 

Demo Download

In this tutorial we are going to create an awesome image gallery which leverages the latest CSS3 and jQuery techniques. The script will be able to scan a folder of images on your web server and build a complete drag and drop lighbox gallery around it.

It will be search-engine friendly and even be compatible with browsers which date back as far as IE6 (although some of the awesomeness is lost).

We are using jQuery, jQuery UI (for the drag and drop) and the fancybox jQuery plugin for the lightbox display in addition to PHP and CSS for interactivity and styling.

Before reading on, I would suggest that you download the example files and have the demo opened in a tab for reference.

So lets start with step one.

Step 1 – XHTML

The main idea is to have PHP as a back-end which will generate the necessary XHTML for each image. The generated code is later included in demo.php and completes the gallery XHTML front-end.

demo.php

view source

print?

01
<!-- The gallery container: -->

02
<div id="gallery">

03

04
<?php

05
/* PHP code, covered in detail in step 3 */

06
?>

07

08
<!-- The droppable share box -->

09
<div class="drop-box">

10
</div>

11

12
</div>

13

14
<div class="clear"></div>

15

16
<!-- This is later converted to the modal window with the url of the image: -->

17
<div id="modal" title="Share this picture">

18
<form>

19
<fieldset>

20
<label for="name">URL of the image</label>

21
<input type="text" name="url" id="url" class="text ui-widget-content ui-corner-all" onfocus="this.select()" />

22
</fieldset>

23
</form>

24

25
</div>

Nothing too fancy here. Notice the modal div – it is used to generate the modal window that is shown when the user drops a picture on the share box. But more on this later on.

The gallery

The gallery

Step 2 – CSS

Now that we have all the markup in place, it is time to style it. First we need to include the CSS files in the head section of the page.

demo.php

view source

print?

1
<link rel="stylesheet" type="text/css" href="demo.css" />

2
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/ui-darkness/jquery-ui.css" type="text/css" media="all" />

3
<link rel="stylesheet" type="text/css" href="fancybox/jquery.fancybox-1.2.6.css">

After we’ve done that, we can start writing the styles.

demo.css

view source

print?

01
body{

02
/* Styling the body */

03
color:white;

04
font-size:13px;

05
background: #222222;

06
font-family:Arial, Helvetica, sans-serif;

07
}

08

09
#gallery{

10
/* The pics container */

11
width:100%;

12
height:580px;

13
position:relative;

14
}

15

16
.pic, .pic a{

17
/* Each picture and the hyperlink inside it */

18
width:100px;

19
height:100px;

20
overflow:hidden;

21
}

22

23
.pic{

24
/* Styles specific to the pic class */

25
position:absolute;

26
border:5px solid #EEEEEE;

27
border-bottom:18px solid #eeeeee;

28

29
/* CSS3 Box Shadow */

30
-moz-box-shadow:2px 2px 3px #333333;

31
-webkit-box-shadow:2px 2px 3px #333333;

32
box-shadow:2px 2px 3px #333333;

33
}

34

35
.pic a{

36
/* Specific styles for the hyperlinks */

37
text-indent:-999px;

38
display:block;

39
/* Setting display to block enables advanced styling for links */

40
}

41

42
.drop-box{

43
/* The share box */

44
width:240px;

45
height:130px;

46
position:absolute;

47
bottom:0;

48
right:0;

49
z-index:-1;

50

51
background:url(img/drop_box.png) no-repeat;

52
}

53

54
.drop-box.active{

55
/* The active style is in effect when there is a pic hovering above the box */

56
background-position:bottom left;

57
}

58

59
label, input{

60
/* The modal dialog URL field */

61
display:block;

62
padding:3px;

63
}

64

65
label{

66
font-size:10px;

67
}

68

69
fieldset{

70
border:0;

71
margin-top:10px;

72
}

73

74
#url{

75
/* The URL field */

76
width:240px;

77
}

One of the classes above, probably needing additional clarification is the pic CSS class. This is used to style the images to look like polaroids. To achieve this, it basically puts a white border around each image.

Also used in the class is the box-shadow CSS3 property, which casts a shadow under each polaroid.

If you’ve looked around the demo of the gallery, you’ve noticed that the images are scattered on the page and rotated in a random fashion. This is done solely with CSS in the PHP side, as you will see in a moment.

The rest of the styles are pretty straightforward and won’t be covered in detail here.

The pics explained

The pics explained

Step 3 – PHP

As you remember, in step 1 we covered the XHTML part and mentioned that PHP is responsible for generating the markup that comprises the individual images. And here is how this is actually done:

demo.php

view source

print?

01
/* Configuration Start */

02
$thumb_directory = 'img/thumbs';

03
$orig_directory = 'img/original';

04
$stage_width=600;

05
$stage_height=400;

06
/* Configuration end */

07

08
$allowed_types=array('jpg','jpeg','gif','png');

09
$file_parts=array();

10
$ext='';

11
$title='';

12
$i=0;

13

14
/* Opening the thumbnail directory and looping through all the thumbs: */

15
$dir_handle = @opendir($thumb_directory) or die("There is an error with your image directory!");

16
$i=1;

17

18
while ($file = readdir($dir_handle))

19
{

20
/* Skipping the system files: */

21
if($file=='.' || $file == '..') continue;

22

23
$file_parts = explode('.',$file);

24
$ext = strtolower(array_pop($file_parts));

25

26
/* Using the file name (withouth the extension) as a image title: */

27
$title = implode('.',$file_parts);

28
$title = htmlspecialchars($title);

29

30
/* If the file extension is allowed: */

31
if(in_array($ext,$allowed_types))

32
{

33
/* Generating random values for the position and rotation: */

34
$left=rand(0,$stage_width);

35
$top=rand(0,400);

36
$rot = rand(-40,40);

37

38
if($top>$stage_height-130 && $left > $stage_width-230)

39
{

40
/* Prevent the images from hiding the drop box */

41
$top-=120+130;

42
$left-=230;

43
}

44

45
/* Outputting each image: */

46
echo '

47

"pic-'.($i++).'" class="pic" style="top:'.$top.'px;left:'.$left.'px;background:url('.$thumb_directory.'/'.$file.') no-repeat 50% 50%; -moz-transform:rotate('.$rot.'deg); -webkit-transform:rotate('.$rot.'deg);">

48

49
class="fancybox" rel="fncbx" href="'.$orig_directory.'/'.$file.'" target="_blank">'.$title.'

50

51

';

52
}

53
}

54

55
/* Closing the directory */

56
closedir($dir_handle);

First, we open the thumbnail directory with opendir (using the @ modifier to prevent any possible errors from getting shown to the user) and looping through all the images.

In the loop, we skip the non-image files and generate some XHTML code for each image, which is directly printed to the screen.

As mentioned in the CSS part, PHP handles the rotation and scattering of the images on the page. Each image is positioned at random X and Y coordinates, and rotated in an angle between -40 and 40 degrees (to prevent upside-down images). Those are generated with the use of the rand() PHP function and included as CSS styles in the picture’s style attribute.

There are two image folders used by the gallery – thumbs, which holds the 100×100 px thumbnails, and original, which holds the big versions of the images. It is important that the thumbnail and original image have the same name, otherwise the gallery won’t function properly.

The only thing left is to throw in some interactivity.

Step 4 – jQuery

We now have a good looking CSS gallery on our hands. But that means nothing if we cant drag the pretty pictures around the screen and zoom them in a fancy lightbox display, does it?

This is where jQuery comes into play.

script.js

view source

print?

01
$(document).ready(function(){

02
// Executed once all the page elements are loaded

03
var preventClick=false;

04
$(".pic a").bind("click",function(e){

05

06
/* This function stops the drag from firing a click event and showing the lightbox */

07
if(preventClick)

08
{

09
e.stopImmediatePropagation();

10
e.preventDefault();

11
}

12
});

13

14
$(".pic").draggable({

15

16
/* Converting the images into draggable objects */

17
containment: 'parent',

18
start: function(e,ui){

19
/* This will stop clicks from occuring while dragging */

20
preventClick=true;

21
},

22
stop: function(e, ui) {

23
/* Wait for 250 milliseconds before re-enabling the clicks */

24
setTimeout(function(){ preventClick=false; }, 250);

25
}

26
});

27

28
$('.pic').mousedown(function(e){

29
/* Executed on image click */

30
var maxZ = 0;

31

32
/* Find the max z-index property: */

33
$('.pic').each(function(){

34
var thisZ = parseInt($(this).css('zIndex'))

35
if(thisZ>maxZ) maxZ=thisZ;

36
});

37

38
/* Clicks can occur in the picture container (with class pic) and in the link inside it */

39
if($(e.target).hasClass("pic"))

40
{

41
/* Show the clicked image on top of all the others: */

42
$(e.target).css({zIndex:maxZ+1});

43
}

44
else $(e.target).closest('.pic').css({zIndex:maxZ+1});

45
});

46

47
/* Converting all the links to a fancybox gallery */

48
$("a.fancybox").fancybox({

49
zoomSpeedIn: 300,

50
zoomSpeedOut: 300,

51
overlayShow:false

52
});

53

54
/* Converting the share box into a droppable: */

55
$('.drop-box').droppable({

56
hoverClass: 'active',

57
drop:function(event,ui){

58

59
/* Fill the URL text field with the URL of the image. */

60
/* The id of the image is appended as a hash #pic-123 */

61
$('#url').val(location.href.replace(location.hash,'')+'#' + ui.draggable.attr('id'));

62
$('#modal').dialog('open');

63
}

64
});

65

66
/* Converts the div with id="modal" into a modal window  */

67
$("#modal").dialog({

68
bgiframe: true,

69
modal: true,

70
autoOpen:false,

71

72
buttons: {

73
Ok: function() {

74
$(this).dialog('close');

75
}

76
}

77
});

78

79
if(location.hash.indexOf('#pic-')!=-1)

80
{

81
/* Checks whether a hash is present in the URL */

82
/* and shows the respective image */

83
$(location.hash+' a.fancybox').click();

84
}

85
});

First we are binding a click function to the images, which prevents the lightbox from showing once we start dragging the pic around.

After this we make all the pictures draggable, and then we set up the lightbox.

Later we turn the “Drop to share” box into a droppable, which enables it to detect when a picture is hovered and dropped. This allows us to add a special hover style to the container, and to open the modal window on drop.

The modal window itself is a user interface component that comes with jQuery UI. It hides all the page elements under a semi-transparent overlay, and thus blocking them for the user. The only thing occupying the their attention is the message window, which in our case holds the text box with the URL of the image, as defined in the div with id of modal in step one.

Last, we have a few lines of code which check whether a hash of the type #pic-123 is present in the URL, which would cause the respective image to be shown in the lightbox on page load.

With this our awesome CSS3 gallery is complete!

Conclusion

Today we created a fancy gallery, which uses a wide set of web technologies to bring you a new kind of dynamic experience.

In addition, it is extremely easy to add to an existing site – you just need upload it and provide a folder with images, no databases required.

You are free to modify and use this gallery in your own sites. Be sure to share all your awesome creations based on this gallery with the community via our Tutorial Mash-ups (above the comment section).

Deixe uma Resposta

Preencha os seus detalhes abaixo ou clique num ícone para iniciar sessão:

Logótipo da WordPress.com

Está a comentar usando a sua conta WordPress.com Terminar Sessão /  Alterar )

Google photo

Está a comentar usando a sua conta Google Terminar Sessão /  Alterar )

Imagem do Twitter

Está a comentar usando a sua conta Twitter Terminar Sessão /  Alterar )

Facebook photo

Está a comentar usando a sua conta Facebook Terminar Sessão /  Alterar )

Connecting to %s