Simplest Lightbox Code in the World

I was working on a web page where, in the past, the design was to use pop-up boxes. But pop-up boxes are so 1990s. Now, the thing is lightboxes. You’ve seen them. That’s when you get, essentially, a pop-up box on your screen, except it’s not another browser window and the web site in the background is often grayed out.

This page was a big table of information. First I tried using TablePress in a WordPress installation. But putting links in all those table cells was not going to happen. So I chucked that and found DataTables. It did the same kind of things as TablePress, but without the blog. And this way, I could put all the data into a real database and pull it that way, which was far superior.

Once the table part was done, there was the lightbox part. I tried Lightbox2 first, since I’d used that on a web site a decade ago. That failed quickly as it only does images and captions. I needed text in my lightboxes. I tried a couple others but had problems with them. I can’t even remember all the specifics, but they didn’t want to work easily. Certainly not as easily as DataTables did.

I found where people shared the code needed to program lightboxes, but they went on and on and on. If it was that complicated, I might as well use a program that someone has already written (which I’d already tried.)

And then I found this page from Superior Web Solutions, a Toronto web designer. They claimed their code was “the most simple way to code a Lightbox”, and boy is it.

I had some trouble with the code when I had too much content and it didn’t scroll, but I finally figured that out — they mentioned it in a comment that I hadn’t noticed. But the one thing missing was clicking on the background. I like my lightboxes where you can close the box by clicking outside of it and their code didn’t do that.

I struggled to try things to make that happen and came up short. Then I let my subconscious figure it out. It can do that a lot, especially with programming.

Out of nowhere, I had the solution. I added a global variable. It was so simple. All the times I tried to close the lightbox without knowing which one was open (I had a page with 308 lightboxes), all I needed was to know which was open. So I defined a global variable. When I opened the lightbox, I set the global variable to the lightbox number. I made the background box clickable and called the same display/hide function, but with the global variable instead.


So now I have the simplest lightbox code in the world, and it closes when you click the background. I’m a happy camper.

Go ahead. Try it. :-)

Leave a Reply

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