
The Code:
The HTML required for the lightbox is very less, here it is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
<!DOCTYPE html> <html> <head> <title>Lightbox Example | Code Affair</title> <style> #l_out{ display:none; position:fixed; left:0; top:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1; } #l_in{ display:none; position:fixed; left:10%; top:10%; width:80%; height:80%; background:white; border-radius:5px; z-index:2; } #l_in iframe{ width:100%; height:100%; } #trigger{ background:#17aa56; color:#fff; border-radius:7px; box-shadow:0 5px #119e4d; padding:10px 20px 10px 20px; margin:10px; display:inline-block; cursor:pointer; border:none; } #trigger:focus{ outline:none; } #trigger:active{ box-shadow:none; } </style> <script src="jquery.js"></script> <script type="text/javascript"> //js code goes here </script> </head> <body> <button id="trigger">Click Me!</button> <div id="l_out" class="close"></div> <div id="l_in"> <iframe src="http://codeaffair.com/"></iframe> </div> </body> </html> |
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:
1 2 3 4 5 6 7 8 9 10 |
jQuery(document).ready(function($){ $("#trigger").on("click",function(){ $("#l_out").fadeIn(); $("#l_in").fadeIn(); }); $(".close").on("click",function(){ $("#l_out").fadeOut(); $("#l_in").fadeOut(); }); }); |
DEMO
Here is what the above could would render:DEMO
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!
Follow Us