Lightbox using CSS-javascript

Published 29 Jan by SuperNOVA

Lightbox using CSS-javascriptLightboxes are Modal Windows that might be useful in cases where you want to show important information to the user like a discount offer or something. They can also serve as a very useful alternative for popups. Lets try and create a lightbox using just CSS and jQuery!

The Code:

The HTML required for the lightbox is very less, here it is:

As you can see all you need is an outer div and an inside div which are hidden, you could have them nested as well, but I chose two distinct divs. Inside the inner div you can put any HTML content that you want to display.

In the CSS, we have defined how the lightbox will be shown. We have positioned the inner and outer divs, given them widths and backgrounds.

Now what’s left is the js code that will trigger the showing/hiding of the lightbox. I have used jQuery in my code because its already used in most of my projects, but you can easily define the event handlers in raw js too. So, here is the code:

To hide the lightbox I have attached an event handler on a class because that provides the flexibility to hide the lightbox by multiple elements like a close button, the background of the modal window etc.


Here is what the above could would render:

Expanding The Script:

This is a very basic example of course but it can be very useful in your own projects as this would eliminate the need for heavy plugins. You can even eliminate the need for jQuery as only the click event listeners are required for its working.
You can further improve the script by using proper images etc in the lightbox and make a gallery.
Further transitions and effects can be added to the script to make the overall effect look good! If you have a code/suggestion that can make the script even simpler, don’t forget to share it, because we grow when we interact!