Home & blog  /  Scripts  /  view post  / RSS

Lightbox and lightbox dialog

Overview

This script acts as both a jQuery lightbox plugin and a lightbox-assisted simulation of in-built browser dialog methods. In both respects it's very versatile, giving you full control over the look and behavior of the script.

Usage

Elements within page

Call the lightbox on an element returned by a jQuery selector (see examples).

$(selector).lightbox(noFade, autoDisappear, noLightbox, noClose);

noFade (bool, default: false) - if true, lightbox transitions simply, without fade in/out effect

autoDisappear (int) - the number of seconds after which the lightbox should close automatically. If not set, the lightbox will not close until told to.

noLightbox (bool, default: false) - if true, the element returned by the jQuery selector is still centred, but without the screen behind it fading to dark

noClose (bool, default: false) - if true, the lightbox cannot be closed by any means, except via calling hidelightbox()

Absent elements

The script can also be used to load elements NOT present in the page, such as remote images or even entire pages. To do this, simply run the lightbox on the URL to the resource. See Example: absent elements, below.

In the event of loading absent pages, the iframe dimensions can be modified in the confif section (see notes).

Dialogs

To use the lightbox to simulate a browser dialog (alert or confirm), call lbDialog(params);, where params is an object of parameter/value pairings from the following:

content (string) - the message to display in the dialog

OKButton (obj) - allows you to customise the 'OK' button by passing an object with the following params:

-- text (string) - the button text

-- callback (func) - a callback function to be invoked when the button is clicked

-- noLBClose (bool, default: false) - if true, clicking the button will not close the lightbox

cancelButton (obj) - pass this if you want a confirm, not alert. This is your negative button. Works like OKButton

css (obj) - an object of property/value CSS pairings to further style your dialog

error (bool, default: false) - if true, puts a red 'error' heading above your dialog's message

success (bool, default: false) - as with error, but writes 'success' in green

autoDisappear (int) - the number of seconds after which the lightbox should close automatically. If not set, the lightbox will not close until told to

Utility function - hidelightbox()

This useful function allows you to close the lightbox from within your scripts, rather than requiring user input to close it.

hidelightbox(noFade, callback);

noFade (bool, default: false) - if true, the lightbox disappears simply, without fade

callback (func) - a callback function to be execute once the lightbox has vanished

Utility plugin - centreElement()

This is used by the lightbox to centre the requested element, but can be used independently of it. Run it on element(s) returned by a jQuery selector and it will pick them up and centre it/them absolutely in the viewport.

$(selector).centreElement(horiz, vert, justReturnedValues);

horiz bool - if true, centres element on X axis (default: true)

vert bool - if true, centres element on Y axis (default: true)

justReturnValues bool - if true, returns centred coordinates as an array ([left, right]) but doesn't reposition element (default: false)

Example: page element

Click here to see the doggy.

Here's the source code behind this example, applied the link's href:

$('#dog').lightbox();

Example: dialogs

Click here to simulate an alert

Here's the source code behind this example, applied the link's href:

1lbdialog({

2     content: 'Hello, world!'

3})

Click here to simulate a confirm().

Here's the source code behind this example, applied the link's href:

1lbdialog({

2     content: 'Go back to homepage?',

3     cancelButton: {

4         text: "not yet"

5     },

6     OKButton: {

7         text: "Yeah, let's go",

8         callback: function() {

9             location.href = 'index.php';

10         }

11     }

12});

Example: absent elements

Click to fetch and display the PHP logo

Here's the code behind this example:

'http://static.php.net/www.php.net/images/php.gif'.lightbox();

Click to fetch and display the PHP homepage

Here's the code behind this example:

'http://www.php.net'.lightbox();

Notes

Global config

You can set permanent preferences in the script file itself, in the config section. There you can set the default opacity and colour of the fade, as well as default CSS for dialogs. Note that, with dialogs, styles set in the additionalCSS parameter (if passed) trump the config if there is a clash.

Lightbox closure methods

The lightbox can be closed in a number of ways, namely:

  • by clicking outside of the central element, on the lightbox
  • by clicking any button within the central element that does not have .noLBClose
  • by clicking any element in the central element that has .close
  • by pressing the escape key
  • by calling hideLightbox() (see above) from within a script

All of these apply also for lbdialog(), except for clicking the faded screen. This is because with an in-built dialog you cannot close it by clicking outside it - only by clicking one of its buttons or pressing escape. Note that, if escape is pressed whilst a simulated confirm() is showing, it is deemed to return false.

DOM

When calling lightbox(), if the element being centred is picked out of the DOM is not a first-generated child of <body>, it is picked up from its current position and reinserted as such, for ease of positioning.

Loading jQuery

By default, this script assumes you're loading jQuery via Google (why might you do this?). If, instead, you're loading jQuery from a local copy in your site folder, update the document ready handler (DRH) in the script file:

1//loading jQuery via Google

2google.setonloadcallback(function() { ...

3 

4//loading jQuery from local copy (use either)

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

6$(function() {...

post new comment

Comments (20)

Eugene, at 15/12/'10 16:39, said:
At line 286 in your code you are not closeing the paragraph tag you opened.  This causes an error in IE7 and IE8
Mitya, at 15/12/'10 20:40, said:
Eugine - mark-up errors are unlikely to cause JS errors, even in IE, however I have fixed the issue in question. Thanks for bringing it to my attention. Expect an update to Lightbox Dialog soon - I've added some more features to it.
Asfhy, at 22/12/'10 09:18, said:
It can cause errors. New versions of most browsers validates the new content generated by JS automatically, so if you do not close a tag, it can cause an exception because the not valid new code is beign inserted on an element.
seoma, at 2/02/'11 23:03, said:
Great post! I have been trying to customize the buttons using css but no luck. Any help will be appreciated
franz, at 15/07/'11 09:45, said:
hi, how can the "ok" and the "cancelbutton" get there own css?
thank you verry much!
Mitya, at 15/07/'11 10:41, said:
See the lbdialog_css object at the top of the script. You can put styles in there. I think I'll re-do this script at some point so styling is handled completely externally, in CSS, not in the script.
franz, at 15/07/'11 11:04, said:
thank you mitya for your answer. but how can i give the "ok" and "cancelbutton" a sepperate css? i think there i can only style the box and not the buttons. 

       lbdialog_css: {
              borderRadius: 10,
              width: 400,
              boxShadow: '0 0 32px #222323'
       },


thank you verry much again!
Mitya, at 15/07/'11 11:23, said:
Actually I've just realised there's no reason why you can't style these buttons using ordinary CSS. If you Dragonfly/Firebug the examples on this page above, you'll see the buttons are styled, using styles in my site's general stylesheet.

LB dialogs have the id 'lightboxdialog' so you can target buttons inside it with a selector like:

#lightboxdialog button { background: #f90; }
franz, at 15/07/'11 12:11, said:
thank you - but i wanted to style each button different. with this css the buttons have the same style. 
it´s o.k. if there is no solution. but it would look better. for exmaple "ok" with a green background an "cancel" with a red background.
thank you!
Mitya, at 15/07/'11 12:58, said:
If you change line 322 in the script file to become:

$(but).css({'float': buttons[e] == 'OK' ? 'right' : 'left'}).attr('id', 'lbdialog_'+(buttons[e] == 'OK' ? 'ok' : 'cancel'));

...you'll find each button has its own ID, either lbdialog_ok or lbdialog_cancel. I'll add this to the download script later on.
franz, at 15/07/'11 15:03, said:
THANK YOU VERRY MUCH!!!
Bhushan, at 13/08/'11 05:34, said:
How to set size of lightbox
James, at 30/08/'11 12:25, said:
Ello, I am trying to use this on a gallery. After clicking an image it goes into the lightbox and when closing the lightbox the image stays on screen and doesn't go back to its position in the DOM. Any ideas why it is doing this? I am using this to trigger the lightbox effect

$("#Flickr img").click(function(){
$(this).lightbox();
});  
Mitya, at 30/08/'11 12:29, said:
Hi James - I've never come across this issue before. Do you get any JS errors? Have you Firebugged/Dragonflied the image to see if, perhaps, some CSS is forcing it to remain visible, perhaps with an !important?
James, at 1/09/'11 15:42, said:
Don't think I got a copy of this issue any more I should of made a jsfiddle. I didn't find a fix. I will try and replicate it and letcha know!
James, at 9/09/'11 12:43, said:
I was trying to do this -
<a href="javascript:$('#dog').lightbox();" ><img src="Lightbox-and-lightbox-dialog-99_files/dog.jpg" id="dog"></a>

When you click on the image it disappears. I can duplicate the image and hide it like your dog example but is there not a way that doesn't replicate the image until the image is clicked on?
MItya, at 11/09/'11 11:58, said:
Hi James

I can't imagine why you'd want to show in a lightbox something that is already visible in the page, but here's your options:

- duplicate the element. This can be done with $('#mypic').clone().lightbox() (though note that this will create a clone each time the lightbox is loaded, so you might want to clone instead just once on page load)

- open the image in absent file mode (see documentation), i.e. 'path/to/image.jpg'.lightbox()
James Gardner, at 12/09/'11 13:46, said:
I am loading thumbnails from flickr and when a thumb is clicked it loads the original image.

Cheers
Mitya, at 12/09/'11 14:02, said:
Hi James (didn't realise it was you :))

So the fullsize image and the thumbnail are the same element? Does that mean you're resizing the fullsize image as a thumbnail via CSS? Not a good idea if so since the compression will be rubbish. Try either of the methods I suggested.

Cheers
m1st0, at 2/12/'11 22:41, said:
I had various messages posting to the user which required differing heights to the light box.  Unfortunately, setting specific heights did not allow for either long or short messages respectively.  So I changed the following changes so the light box height is set to auto.  Still allows the light box to center somewhat as if it were 300 pixels in height.  May not work in all browsers (2 lines changed, sorry I didn't fix the code to do it correctly for now since my site needed the change now): 

lightboxConfig = {
       lbOpacity:       .6,
       lbBackground: '444',
       lbdialog_defaultHeight: 'auto', //default height of lightbox replcement dialog box (i.e. alert/confirm) changed my m1st0;
       lbdialog_allowCloseByClickingLightbox: false, //see notes at top
       lbdialog_css: {
              borderRadius: 10,

           var left = (self.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth)) / 2 - (temp_elWidth / 2) + scrollX;
       
           var temp_elHeight = parseInt(el.currentStyle ? el.currentStyle.height : getComputedStyle(el, null).height);
           if (isNaN(temp_elHeight)) { $(el).css('height', 'auto'); temp_elHeight = 300; } // " " " changed by m1st0 for correct height
           var top = (self.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight)) / 2 - (temp_elHeight / 2) + scrollY;
post new comment
[ cancel ]