« Previous

YUI Based Lightbox - Final

Posted on January 1, 2008
Filed Under Javascript | 37 Comments
Tags: , , , ,


Download Latest Source Code | change log
Download YUI
Thumbnail-less demonstration
Thumbnail-enabled demonstration
Create your own

My previous YUI implementation of the lightbox, which was released for beta evaluation, now has nearly gone gold. This page will be devoted for upcoming updates and bug fixes. So if you've found any bugs, feel free to report them in the comment section of this post.

Also, I would like to thank many who reported bugs and gave feedbacks after the release of previous image lightbox. As many have requested, I implemented navigation for the new lightbox. In addition to the navigation, numerous new features have been added and bugs have been fixed.

yui-gallery-ss1.gifyui-gallery-ss2.gif

What's New

The most significant change in this version of the lightbox is that image thumbnails are no longer required for creating lightbox instance. That implies that you can create an image gallery without the presence of image thumbnails. The more exciting aspect of this new feature is that you can virtually grab any image from the internet and include it in your gallery. Test-drive this new feature.

Below is the detailed list:

  • Ability to view full size and auto-fit version of the image
  • Settings for changing background mask opacity and color
  • keyboard shortcuts
  • Tooltip panel for displaying extra information
  • Navigation control toolbar
  • Image transition effect
  • External stylesheet for styling

Bug Fixes

  • Fixed image goes outside of viewport bug
  • Removed extra scrollbar when the image can be fit into the viewport

The lightbox has been tested in Firefox 2.0.0.6, IE 7, Opera 9.21.

Installation

Download the latest lightbox source and unpack it to your project directory.

Include the following files to your page:

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.4.1/build/assets/skins/sam/skin.css">
<script type="text/javascript" src="http://yui.yahooapis.com/2.4.1/build/utilities/utilities.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.4.1/build/container/container-min.js"></script>
<link rel="stylesheet" type="text/css" href="[PATH_TO_LIGHTBOX]/lightbox/lightbox.css">
<script type="text/javascript" src="[PATH_TO_LIGHTBOX]/lightbox/Lightbox-min.js"></script>

If you prefer to serve above files locally, you can download YUI from here.

JavaScript Code

First, create a data source object to represent the photo gallery:

var dataSource = {
    image1:{url:"photos/1.jpg", title:"hi", text: "shot"},
    image2:{url:"photos/2.jpg", title: "tes"}
    image3:{url:"photos/3.jpg"}
    //...and so on
};

If you need to add more images to the gallery, simply add more tuples to the data source. For each tuples, attributes title and text are optional.

After data source object has been created, you can instantiate an instance of the lightbox:

var lightbox = new YAHOO.com.thecodecentral.Lightbox(dataSource);

To show the lightbox, simply call

lightbox.show();
or
lightbox.show(imageId);

That's all.

Putting Everything Together

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.4.1/build/assets/skins/sam/skin.css">
<script type="text/javascript" src="http://yui.yahooapis.com/2.4.1/build/utilities/utilities.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.4.1/build/container/container-min.js"></script>
<link rel="stylesheet" type="text/css" href="[PATH_TO_LIGHTBOX]/lightbox/lightbox.css">
<script type="text/javascript" src="[PATH_TO_LIGHTBOX]/lightbox/Lightbox-min.js"></script>
<script type="text/javascript">
//defer the instantiation of Lightbox. Call when the page has finished loading.
init = function(){
   //creating a data source object
  var dataSource = {
    image1:{url:"photos/2.jpg", title:"hi", text: "shot"},
    image2:{url:"photos/4.jpg", title: "tes"}
    //and so on
  };

  //Instantiate a Lightbox object
  var lightbox = new YAHOO.com.thecodecentral.Lightbox(dataSource);
}
YAHOO.util.Event.on(window, 'load', init);
</script>

Optional Settings

If you are not happy with the default settings that bundled with the lightbox, feel free to modify them at your will. Here's a list of settings you can modify:

Name Default Value Description
id tcc_showImgPanel Set HTML ID attribute of the lightbox. Used only when create multiple instances of lightbox
maskOpacity Set by YUI Opacity of the background mask
maskBgColor Set by YUI Color of the background mask
modal true Set this to true will block user inputs to other elements below the mask
hasThumbnails true If set to true, the lightbox will attach click event to images which IDs are specified in the data source
ctrlVisible true Visibility of the control panel
ctrlOpacity .5 Control panel's opacity
effect true Fade in effect between images
effectDuration 1 Effect duration in second
tooltip true Visibility of the tooltip
tooltipOpacity .9 Opacity of the tooltip

Example:

  //Instantiate a Lightbox object
  var lightbox = new YAHOO.com.thecodecentral.Lightbox(dataSource, {
    id: 'showtcc',
    maskOpacity: .8,
    maskBgColor: '#000',
    modal: true,
    hasThumbnails: true,
    ctrlVisible: true,
    ctrlOpacity: .5,
    effect: true,
    effectDuration: 1,
    tooltip: true,
    tooltipOpacity: .9
  })

Styling the Lightbox

You can style the lightbox by editing lightbox.css, which can be found under the lightbox distribution. If you are a CSS guru, things would be self-explanatory.

Image Preloading

Since RC2, you are given the ability to preload images before bringing up the lightbox. Preloading images is easy, simple call preloadAll() method on the lightbox instance:

lightbox.preloadAll();

If you want to be notified during the preloading process, you can subscribe to the following events:

  • preloadStartEvent - fired before preloading of single image
  • preloadCompleteEvent - fired after preloading of single image
  • preloadCompleteEvent - fired when all images have been preloaded

You don't need to to subscribe to all them, just the ones you are interested at. Here's a code snip on how:

  lightbox.lightboxPanel.preloadStartEvent.subscribe(function(e, info){
      //Do something, e.g., update UI for preloading progress
      alert(info.imageId + info.ds.url);
  });
  lightbox.lightboxPanel.preloadCompleteEvent.subscribe(function(e, info){
       //Do something, e.g., update UI for preloading progress
       alert(info.imageId + info.ds.url);
  });
  lightbox.lightboxPanel.preloadAllCompleteEvent.subscribe(function(e, numPreloaded){
     //Do something, e.g., update UI for preloading progress
     alert(numPreloaded + ' images preloaded');
  });

Inside of the event handler, you can access information about current image through the second argument of the handler:

For preloadStartEvent and preloadCompleteEvent, this argument is an associative array with two attributes:
imageId: the image ID you specified in the data source
ds: the data source tuple associated with this image ID

For preloadCompleteEvent, this argument is the number of images that preloaded.

You can find more information on YUI's event framework here. I've also compiled a list of YUI's event handlers.

Change Log

lightbox-final-RC4.zip (4/19/2008)
Bug Fix: When creating multiple instances of the lightbox, the toolbar of all instances use the same ID.
RC4 forces each instance of the lightbox uses a unique ID for its toolbar.
--------------------------------------------------------------------------------------------------
lightbox-final-RC3.zip (1/7/2008)
Bug Fix: Updated help file. Removed Ctrl + Click shortcut in help file, replaced by Space bar
--------------------------------------------------------------------------------------------------
lightbox-final-RC2.zip (1/4/2008)
Bug Fix: Change variable name "pagepageScrollTopValue" to "pageScrollTopValue"
Enhancement: Added preload all images feature
--------------------------------------------------------------------------------------------------
lightbox-final-RC1.zip (1/1/2008)
Initial release

Thank you for visiting and Happy New Year!

Related Links

Go to Top

More interesting posts ...

Comments
37 Comments so far
  1. Daniel Jalkut January 4, 2008 4:55 pm

    Thanks a lot for making this available. I really like the aesthetics you're going for a lot more than in some other solutions I've seen.

    You may be pleased to know that it seems to work pretty well in Safari. I found a bug however, that was only exposed after trying it with the latest and greatest WebKit from Apple. Am I right in assuming that every instance of "pagepage" in the script should actually be "page" ? I did this global replace and things were a lot better.

    One thing I'd like to be able to do is to preload images before showing any UI. In other words I'd like to be able to have the images loading in the background before the user clicks any thumbnail. Is this possible?

    Thanks again,
    Daniel

  2. Cuong January 4, 2008 9:09 pm

    Thank you for your generous support.

    Indeed the variable name "pagepage" is a bug. I wasn't aware of how it got into the source, probably due to some mindless copy and paste.

    I changed the "pagepage" to "page", as well updated the source code for background preloading. Please check updated documentation for more detail. Thanks.

  3. Daniel Jalkut January 5, 2008 12:34 am

    Wow! I'm really impressed. Thanks for making these changes so quickly. You're doing a great job.

  4. Dennison Uy - Graphic Designer January 6, 2008 8:37 am

    Impressive work. My only issue with this is that it is a bit heavy and could have been implemented more elegantly with pure DOM manipulation so I really do not see its advantage over something lightweight like lightbox JS. Also, I couldn't get the image resizing to work, no matter how many times I try to do control click

  5. Cuong January 7, 2008 6:09 pm

    @Dennison

    The manual is a little bit outdated, the keyboard shortcut for resizing is Space Bar/Up Arrow. I'll update the manual/screenshots soon.

    Speaking of advantages, the biggest one is the ability to display full size and best fit version of a image, which is my initial motivation of making this lightbox. On top of that, I added thumbnail-less feature. With this feature, you can easily create a photo gallery by feeding the lightbox a image source. Test it here

    The end product of this is similar to those XML flash gallery, but the difference is without security restriction. So you can grab some random images from the internet and create a slide show from them. Also this lightbox is highly configurable. For each instance of the lightbox, you can change many attributes such as maskBgColor on the fly.

    I am not saying this is lightbox is superior than others, but just pointing out the unique features. Hopefully it helps.

  6. Tarique Sani February 22, 2008 11:28 pm

    Great Effort! would like to request a small feature - the picture should resize and recenter if the size of the browser window changes

  7. Ryan February 29, 2008 3:31 pm

    This looks great, but I'm looking for help with one more feature. I'd like to use your code in a widget that's hosted within an iframe on a page I don't fully control. I'd like the image to fill the entire window rather than only the iframe document. What kind of changes would be necessary? I thought just turning all the document.createElement methods to parent.document.createElement would do the trick, but no luck.

  8. Ryan March 1, 2008 1:27 am

    Actually, I think I figured it out. Rather than directly call the YUI files in my iframe with and tags, I used the DHTML loading ideas here to add the files into parent.document:
    http://www.codehouse.com/javascript/articles/external/

  9. serkan March 1, 2008 8:53 am

    thank you

  10. Edith March 12, 2008 1:21 pm

    Hi, I was exactly looking for a lightbox like yours, working without thumbnails. But unfortunately I can't make it work.

    http://www.zerosetteaccordions.com/photogallery.php

    lightbox is not defined
    onclick(click clientX=0, clientY=0)

    I've used exactly your code and correctly included
    Lightbox-min.js and lightbox.css.

    Can you please give me a hint what I'm missing??
    Thank you so much!

  11. Cuong March 12, 2008 9:31 pm

    @Edith:

    Two things:
    1) Move the variable lightbox out of the init function, so it can be seen by rest of the code.

    2) Instead of Lightbox.show(), try lightbox.show().

    Cheer!

    var lightbox;
    var init = function(){
      var dataSource = {
        image1:{url:"http://www.zerosetteaccordions.com/assets/images/corporate_folder.gif", title:"hi", text: "shot"},
        image2:{url:"http://www.zerosetteaccordions.com/assets/images/cdummy_catalogue.jpg", title: "tes"}
        //and so on
      };
      //Instantiate a Lightbox object
      lightbox = new YAHOO.com.thecodecentral.Lightbox(dataSource);
    }
    
  12. Edith March 13, 2008 6:51 am

    @cuong:

    You are great! Let me buy you a beer!!!

    Thanks a lot!

  13. Drew Freyling March 23, 2008 4:38 am

    Nice work guys. I reckon this deserves its own project on Google Code or the like for future updates.

    For those using YUI's Font package, you can modify the following lines of the stylesheet to conform the font size percentages and predefined font degradation path:

    .yui-skin-sam .tcc_imageTooltip .bd { background-color: #e4e4e4; border: 5px solid #666; font-size: 93%; font-family:Verdana}
    
    .yui-skin-sam .tcc_imageHelPanel .bd { background-color: #e4e4e4; border: 5px solid #666; font-size: 93%; font-family:Verdana}
    
    .yui-skin-sam .tcc_lightboxLoader a{color: #666;font-size: 100%;text-decoration: none;}
    
  14. JOSEPH March 25, 2008 2:04 am

    IM trying to use your lighbox-mini browser
    its working when i am using a page on my server
    my question is --- how can i call the light box mini-browser
    when i am on any page (not in my server), so i will have the backgrouon page = the web site page not mine and in the ligth box browser - my page -- that i already figer how to change the src of the light box
    how it will work ?
    i am calling a js file that located in my web site (i click a favorit link that open the js file,
    then in the js file i am loading the yui js file and calling the mini-browser

    at this point - its faild calling the mini-browser
    , i tryied to call different yui function like the 'hello world msg' and it working

    please let me know what i am doing wrong

    thank you.

  15. [...] YUI based Lightbox : Yahoo! User Interface Library (YUI) based Lightbox effects written by thecodecentral.com link [...]

  16. Neil April 9, 2008 9:36 am

    I love your YUI lightbox but I am having trouble with multiple instances on the same page. In the following example, note that only the third (and last) instance of the lightbox displays the navigational controls... even though ctrlVisible is "true" for all instances:

    http://www.rrussellbuilders.com/content/Homes_Now_Available_GALLERY.aspx

    Am I doing something wrong or is this a bug?

  17. Cuong April 19, 2008 10:23 pm

    Hi Neil,

    Sorry for the delay as I've been really busy lately.

    I checked your site and ran roughly through my code, that problem was all the controls were using the same ID. Please download this version of the code to see if it fixes the problem.

    Also see:
    http://thecodecentral.com/2008/01/01/yui-based-lightbox-final#change_log

  18. [...] Vielleicht hilft dir da aber auch der Abschnitt "Image Preloading" in dem Artikel YUI Based Lightbox - Final weiter. mfg Maik __________________ Beantwortete Fragen bzw. gel?ste Themen bitte als erledigt [...]

  19. shubelal kumar September 12, 2008 12:13 am

    Dear all

    How can implement login panel in Light box if any can suggest me so please me link.

    thanks

  20. Daniel Gardner September 13, 2008 6:53 pm

    This is a great gallery! Thanks for making it available.

    I've run into a sad bug. I set up a gallery and downloaded YUI today and Chrome and FF read it perfectly but my IE7 won't touch it. Only shows thumbnails, but doesn't offer to click them (i.e. the thumbnails aren't clickable.)

    However, the demo here at codecentral works fine on my IE7. Any help guys? Thanks!

    here's where I'm using it:
    http://www.TropicalPunch.tv/gallery

  21. Daniel Gardner September 15, 2008 5:32 am

    Update to above comment: I changed the URL of where I'm using it. Here's the corrected location:

    http://www.tropicalpunch.tv/gallery/backup/

    If anyone knows what's wrong, please advice. I need helps.

  22. Cuong September 30, 2008 8:29 am

    Hi Daniel, sorry for the delayed response. I have been away from my blog for away. After talking look at your code, I found a the code which causes the problem.

    In the last line of your datasource, you need to remove the comma. So change this line from

    audience10:{url:"http://www.TropicalPunch.tv/gallery/photos/audience/10.jpg"},
    

    to

    audience10:{url:"http://www.TropicalPunch.tv/gallery/photos/audience/10.jpg"}
    

    IE's parser has problem parsing this code. I made the same mistake way back ago, it's really annoying.

  23. Cuong September 30, 2008 8:39 am

    @shubelal kumar

    I've written another post relating to YUI lightbox which has several examples might get you start.

    http://thecodecentral.com/2007/07/13/creating-lightbox-with-yahoo-user-interface-library

    Take a look at the source code of each example.

  24. [...] YUI Based Lightbox The most significant change in this version of the lightbox is that image thumbnails are no longer required for creating lightbox instance. That implies that you can create an image gallery without the presence of image thumbnails. The more exciting aspect of this new feature is that you can virtually grab any image from the internet and include it in your gallery. [...]

  25. Nata October 25, 2008 11:32 pm

    Hi,
    Thank you for the great code that is easy to use without knowing a lot of details about YUI.
    I was able to make it working the way I want, except positioning the image to the different place (slightly to the righ, but ideally to insert it inside existing element) on the screen. Can you help please pointing me to the function that I can change it.

  26. [...] YUI Based Lightbox [...]

  27. pligg.com November 14, 2008 11:17 pm

    YUI Based Lightbox...

    My previous YUI implementation of the lightbox, which was released for beta evaluation, now has nearly gone gold. This page will be devoted for upcoming updates and bug fixes. So if you've found any bugs, feel free to report them in the comment sectio...

  28. Levi November 18, 2008 3:10 am

    Hi Cuong

    I like your code very much and decided to give it a try in my project.

    If I would like to set "onclick='lightbox.show();'" for my hyperlink text field (ie. without the imageID, as the hyperlink text itself is the image file name. eg. ABC123.jpg),
    how do I write the dataSource?

    I hear from you soon. :)

    var dataSource = {
    image1:{url:"photos/1.jpg", title:"hi", text: "shot"},
    image2:{url:"photos/2.jpg", title: "tes"}
    //...and so on
    };

  29. Levi November 18, 2008 8:59 am

    Hi

    One more question, I was trying to include the line

    into my page header in (ASP Maker) project where the js file is placed in the lightbox folder in my project folder. I got IE error that "Object doesn't support this property or method".

    It works fine while I tried to include JQuery's js files.

    Did I miss something?

    I hear form you soon.

  30. Levi November 18, 2008 9:02 am

    opps... the line is missing...

    script type="text/javascript" src="lightbox/Lightbox-min.js"></script

    (with opening & closing angle brackets)

  31. Ed February 22, 2009 11:06 am

    Can't get the maskOpacity to work with IE7. Firefox and Safari work fine. URL is http://dev.ilikesongs.com/SES Then pick photos.

    lightbox = new YAHOO.com.thecodecentral.Lightbox(dataSource, {
    id: 'showtcc',
    maskOpacity: .8,
    maskBgColor: '#000',
    modal: true,
    hasThumbnails: true,
    ctrlVisible: true,
    ctrlOpacity: .5,
    effect: true,
    effectDuration: 1,
    tooltip: true,
    tooltipOpacity: .9
    })

  32. Michael Newton February 22, 2009 6:29 pm

    I'm disappointed that this doesn't work without Javascript enabled in the browser. All the thumbnail images should be links to the fullsize image, in case there is no Javascript available.

    Other than that it's a good job, but I'll have to fix the lack of graceful degradation before I can use it in my code.

  33. matt March 1, 2009 10:25 am

    This script seems to break on-page navigation. For example, if page foo.html loads Lightbox-min.js, any link to a named anchor on that page will instead show the top of the page.

    For example: example.com/foo.html#bottom

    would show the top of foo.html even if there's an anchor named "bottom" near the bottom of the page.

    I can stop this behavior by removing the script tag for Lightbox-min.js

    Note: even if my code doesn't call any lightbox functions, this scrolling-to-top behavior still occurs.

    Is anyone else seeing this? Is there a fix?

  34. sjJNL April 21, 2009 9:23 am

    I have to open a YUI modal overlay from a Flash piece on a webpage.

    How can I do that?

  35. YOzefff May 15, 2009 1:20 am

    @Michael Newton

    That IS possible ;-)

    for example

    http://www.partygek.nl/agenda/2009-06-28/latinvillage/

    click the thumbnail

    This script is great. Just put the ID on the img tag. Now you can make an A tag and a IMG tag inside. Just make sure the A tag has a onclick that returns false. And ofcourse the href points to your source image and the src points to your thumbnail. You still need to specify the thumbnail in the datasource.

  36. Bill Studer June 20, 2009 12:02 am

    Great work on the YUI Lightbox.

    One small problem I found:

    I'm using a few other YUI components, including Yui Menu. However, I'm not using the Menu's default Sam skin, and I do not include class="yui-skin-sam" in the body tag, only in the div surrounding the Lightbox.

    Anyway, when I close a Lightbox, the script is somehow applying the .yui-skin-sam class and its styling to my Menu's custom skin.

    There is probably a better way to fix this, but I found the easiest way was just to remove the css file:
    /YUI_VERSION/build/assets/skins/sam/skin.css. This file actually contains yui-skin-sam styles for every yui component in the library. The only style Lightbox needs, however, is Yui Container, which is in the file
    /YUI_VERSION/build/container/assets/skins/sam/container.css.

  37. Reiki June 30, 2009 11:06 pm

    Excellent information. Finding a few such solutions has taken hours in the past.

    Thank u.

Leave a Comment

If you would like to make a comment, please fill out the form below.

Name (required)

Email (required)

Website

Comments

Attention
If you want to post source code, please wrap it with <pre> and </pre>

Categories

Polls

  • Tell us who you are:

    I am a...

    View Results

    Loading ... Loading ...