My Code Snippet : Automatically start Lightbox on page load (autoFireLightbox)

lightbox.gifEver wanted to automatically start Lightbox so that it shows an image immediately after the page has loaded? It’s possible!

Someone posted a little Javascript Code Snippet that provides this functionality in the Lightbox Forums. Although the code is OK, it requires editing Lightbox.js, which will of course break when a new version is released (it’s never a clever idea to edit core files).

I took the freedom to modify the implementation a bit (the core hasn’t changed though): Instead of editing your Lightbox.js file, you only need to modify your HTML head element so that it includes the extra functionality of kickstarting Lightbox:

<script src="js/prototype.js" type="text/javascript"></script>
<script src="js/scriptaculous.js?load=effects" type="text/javascript"></script>
<script src="js/lightbox.js" type="text/javascript"></script>

<script type="text/javascript">
// Automagically load Lightbox on Page Load - by Bramus! (https://www.bram.us/)
// Code modded from http://www.huddletogether.com/forum/comments.php?DiscussionID=1269&page=1#Item_0
function autoFireLightbox() {
	//Check if location.hash matches a lightbox-anchor. If so, trigger popup of image.
	setTimeout(function() {
		if(document.location.hash && $(document.location.hash.substr(1)).rel.indexOf('lightbox')!=-1) {
			myLightbox.start($(document.location.hash.substr(1)));
		}},
		250
	);
}
Event.observe(window, 'load', autoFireLightbox, false);
</script>

Note #1: it is important that this extra snippet is placed underneath the 3 javascript includes required by Lightbox as the function calls a variable created within Lightbox.js

Note #2: the reason we’re calling a setTimeout (a 250 milliseconds delay) is to fix an issue in IE where the variable myLightbox would be non-existent immediately after page load.

Note #3: getting a myLightBox is undefined error? Great, you’re using the most recent Lightbox version … and that one requires 1 tiny fix 😉

To now use this functionality make sure you have given your a-element an id …

<a href="images/image-1.jpg" rel="lightbox" id="image001"><img src="images/thumb-1.jpg" width="100" height="40" alt="" /></a>

… and then call the page by adding a # followed by that id:

http://mysite.com/lightbox.html#image001

That’s it, you’re done!

A working demo can be found over at https://www.bram.us/demo/projects/autofirelightbox/#image001

To make things complete: this will not work with flashLightBoxInjector as the swf (or a return from your AJAX call, that’s possible too you know), dynamically builds a list of linked images when the swf is loaded/call has been returned.

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Join the Conversation

56 Comments

  1. Great snippet!

    Thank you for sharing, I have put it to good use. Do you use the same creative commons license as Lightbox? Asking, just to be sure what to do if I repack it and distribute it in e.g. wordpress plugins.

  2. Hi Bramus,
    Just checked out your on-page-load Lightbox script and I think it’s excellent. However, if I’m correct, you still need to mention all your image sources in the code of your page.
    Can you think of a way to refer to a single folder-name in your “a href”?

    I have these huge collections of different image galleries and I think I will go crazy if I have to type hundreds of hidden tags.

    To clarify my issue, this is how my start off page should look like:

    » gallery 1
    » gallery 2
    » gallery 3
    » gallery 4

    These are links to different image galleries in different folders.

    Hope this makes any sense to you.

    If so, can you hand me some clues…?

    Thanks in advance and keep up the good work.

    Korjuin

  3. @ Niklas: Creative Commons indeed (attribution, sharealike, non-commercial)

    @ Korjuin: The image sources indeed need to be specified in your document (viz. the needed HTML for the Lightbox need to be present).

    @ Korjuin: if you use a set of images as set per Lightbox specification via the rel attribute (rel=”lightbox[myset]”) and use the autoFireLightbox functionality, the sets still will be respected, as autoFireLightbox works via the id of an element (viz. as the rel attribute lives outside the id attribute they have no influence on each other.)

    1. Is it to possible to view the image randomly?

      I have an array of image which I want it to be load randomly when the page load.

      function popUp(){
      var images = [],
      index = 0;

      images[0] = ““;

      images[1] = ““;

      images[2] = ““;

      index = Math.floor(Math.random() * images.length);
      document.write(images[index]);
      }

  4. Hey,

    I am trying to use lightbox inside a iframe. The lightbox code works great inside the iframe but i want to start the first image. Would I need to mod this code to acclomplish this?

    //

    Any help would be appreciated. Thank you so much for this script!

  5. Oh yeah, forgot the code but it seemed autoFireLightbox function couldnt find my lightbox rel tags inside the iframe…

  6. @ Ed : you have to add this code inside your iframe (and change the iframe URL to have a hash); or you have to change line #13 to target the iframe (untested, but I think it’s this one here): $('idOfiFrame').myLightbox.start($(document.location.hash.substr(1)));

  7. hey

    great work… although i am a bit new to this but kinda get it… can you please help me .. i cant get it to work for me… im calling it and it does not load at all..?:( any chance you can please send me a simple file with it in..?

    many many thanks
    s

  8. hi
    i wanted to use light box twice in a single page. First when the page loads( as done in your example) and then again when i click on a particular link. Can i be done?

    Thanx
    Prabh

  9. I’m getting an error for myLightBox being undefined in both IE and Firefox 3. I’ve increased the 250 milliseconds to 1000 just to see if that would help. It didn’t.

    Has anyone else had this problem? A fix?

  10. Great script!!!! But…
    this instruction .. and then call the page by adding a # followed by that id: I want to avoid as I want to launch the script on my index page and simply I cannot add any parameters, Is it possible.
    Please answer ASAP.
    Regards,
    Greg

  11. @Greg: If you know the ID of the element, then you can – instead of looking for the page it’s location hash (which the script does) – invoke Lightbox by directly calling it via myLightbox.start($('myId'))

  12. Is their anyway to make this load only on external links in? (i.e so if someone was already browsing your site and clicked home it wouldn’t show up again)

  13. Im having the same issue as Greg and urgently need a way out of it.
    Everything is working great, but I cant use it on my index page.
    Would you mind dumbing it down for me how I go about finding the ID of the element and where to edit the code.
    thanks in advance

  14. Hey Brambus, I came across this page from:
    http://www.ibegin.com/labs/forum/comments.php?DiscussionID=63

    Your set timeout function appears to be a good solution for this problem, although I haven’t tried it yet. I’m not using huddletogether.com’s lightbox, but instead ibegin’s ibox, as shown in the link above. Do you think you could please modify your script above for ibox? (I’m not that good with javascript)

  15. I’m afraid I’m having the same confusion as Di. On this page, http://www.floatfishingconnection.com/xtestpagex.htm I added the additional code and made the changes as specificed to the 2.04 js file, but Frontpage will not allow me to save a webpage with a html#image001 after it? I can honestly say that I’m a little confused as to this image tag thing and how exactly it works?

    What I’m attempting to do is have the promotion of the “steelhead contest” pop up and accounce itself as the page loads automatically, but it just isn’t working?

    Thanks,
    Dj

  16. I am following up on two of the questions (from @al and from @Lista) – I wanted to lad an HTML page instead of an image and it is not following up. Any idea why?

    How can I use:

    image #1

    instead of an image in the href?

  17. Thanks for posting this. I wasn’t looking to auto-fire a lightbox onload, but was trying to figure out how to launch a lightbox via JS – simpler than I thought.

    Thanks!

  18. Thank YOU! After parsing the querystring, writing some unreliable script – I found this. You saved me!

  19. I feel really stupid but I don’t understand how to automatically load the lightbox when the page loads. I just don’t get it from your information above.

    … and then call the page by adding a # followed by that id:

    http://mysite.com/lightbox.html#image001

    I don’t understand what this means. How does the page load the lightbox if there is no onLoad event? What am I missing?

    Any information would be helpful to get my head around it. Thanks.

  20. Searched a long time to find someone that had the ‘lightbox onload’ problem solved. Not a savvy I am so I study the scripts just for fun without the heavy load of knowing what I do…great!

  21. Hi, thank you for your suggestions!
    For version 2.04, I modified the last line of code in “lightbox.js”. This is the new line:
    document.observe(‘dom:loaded’, function () { myLightbox=new Lightbox(); });
    To auto-launch lightbox when page loads (that’s all I needed for my pourposes), I just added a where “id1” is the id of the A tag surrounding the image.
    A BIG thank you to you for your work!

  22. everythings works, except the goddamn image never loads, help!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  23. cooollllllll one firstly i got an error mylistbox is undefined but ,,,
    manage to fix it …………

  24. i replace document.observe(‘dom:loaded’, function() { new Lightbox(); });

    with

    document.observe(‘dom:loaded’, function() { myLightbox = new Lightbox(); });

    then it works……….for me…………….

  25. Hi Bram,
    Thanks for your work. In your posting you say you have to change the ‘html head’, but what is that? The closest I could find are the files index.php but that doesn’t seem similar to the file you have.
    Thanks already & regards,
    Jeroen.

  26. Hello. I’m having some issues with setting up your autoFire Lightbox, even with the corrections cited on the page in Note 3. Basically, my id’s don’t trigger the autoFire effect. I’ve triple-checked all the code and have made sure to apply the changes specified above, as I was using version 2.05. I wonder if it may have something to do with the way my WordPress settings handle permalinks? I will also try using your older Lightbox file as one last shot, and then attempt this with an html page, as opposed to the PHP files used by WordPress, before I throw my hands up in the air, completely.

    Thank you in advance for any clarification you can provide.

    1. Thank you, Bram, for the help you provided in getting my implementation to work! And thanks again for this excellent lightbox addition.

      I wish you much good luck with your endeavors.

  27. Pingback: Anonymous
  28. Can someone help me out and tell me what I am going wrong? I have followed this tutorial, but I can get the page to modal window to load.

    // Automagically load Lightbox on Page Load – by Bramus! (http://www.bram.us/)
    // Code modded from http://www.huddletogether.com/forum/comments.php?DiscussionID=1269&page=1#Item_0
    function autoFireLightbox() {
    //Check if location.hash matches a lightbox-anchor. If so, trigger popup of image.
    setTimeout(function() {
    if(document.location.hash && $(document.location.hash.substr(1)).rel.indexOf(‘lightbox’)!=-1) {
    myLightbox.start($(document.location.hash.substr(1)));
    }},
    250
    );
    }
    Event.observe(window, ‘load’, autoFireLightbox, false);

    I know that it says that you have to call the lightbox.html, but I do not have that html file when I download lightbox and the only thing that it does is shows a thumbnail up in the top right hand corner of the page. Any help is appreciated.

    Thanks,
    Phil

  29. I am not getting this auto-loading working either, does it no longer work with the latest light box code or something? I can’t believe how hard it is to get this to auto start, extremely frustrating. Any help would be greatly appreciated.

  30. Hi! Nice job, man!

    I was thinking how to kill the person who asked me to “change” some functions of Lightbox, in fact, he wanted me to add some functions like Facebook and Twitter buttons… my problem was when the person comes from facebook to show directly a Lightbox…

    Thanks by your code. I changed it and now everything’s fine!

    See ya o/

  31. Clever… 😉
    Very kind of you to share this information.
    It works perfectly. I just needed to change the lightbox.js file in the last line and substitute the line you explained above.

  32. I am having the same trouble as many others trying to get this to work on my index page. I saw the response you provided by invoking lightbox via: myLightbox.start($(‘myId’)), but It is not working for me. Can you paste the entire script with this functionality?

    function autoFireLightbox() {
    //Check if location.hash matches a lightbox-anchor. If so, trigger popup of image.
    setTimeout(function() {
    if(document.location.hash && $(document.location.hash.substr(1)).rel.indexOf(‘lightbox’)!=-1) {
    myLightbox.start($(‘image001’));
    }},
    250
    );
    }
    Event.observe(window, ‘load’, autoFireLightbox, false);

    any help is appreciated

  33. I am trying to do this with Lightbox 2.51. Is there an update for the code so it works with this new version? If not, where can I find the older versions of all the files need to make this work?

    Thanks

  34. I also try to make this work with 2.51v . Someone found a solution, please mail me!

    Thx!

  35. Hye there,

    I need some help for you regarding popup lightbox.

    – how to create lightbox (that will appeared our Facebook fan page) for OpenCart?

    *I mean the popup lightbox will appear on our main page (home)

  36. This is just what I have been looking for for a while now. I too have the newest version of Lightbox (2.51) as some of the other guys and can’t get it to work. Is it possible to modify the code in a way to get it working?

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.