Skip to main content

Designing Your Own Lightbox in Javascript

In nowadays web 2.0 world use of Lightbox is very common. While Lightbox, fancybox (similar to the former) are great scripts and have wide uses, creating a script similar to these is never a bad idea. If you learn, read on else use of one of those scripts, they’re great and easy-to-use.

For those of you who haven’t heard about the script or don’t know what they do, see the following image:

Screenshot og Blackbox - Our own Lightbox clone

Chances are, you might surely have seen it somewhere or the other. These JavaScript libraries are generally used to display some content in kind of like a dialog box (modal one, for those of you who're geeks) while the rest of the content gets blackened. Looks great? Yes it does!

Okay, for those of you still here I wanna confess that I didn’t put enough time knowing how those scripts actually work. I just got an idea myself the other day and thought it just might work. This is not to say that I myself have invented some new way, it’s just that I don’t know how those scripts work but I know one way that gives similar results.

As you can see from the above image, there is not much to a simple Lightbox clone, we have a (1) Blackening effect (2) The content box.

  1. Blackening Effect: For this I’ll create a “div” element on the fly and set its properties such that it has a black color and some transparency, a large z-index means floats on top of the rest of the content and back content (with normal z-index) cannot be interacted with anymore. We’ll fill the current screen with this “div” which will require us to place this element at the topmost and leftmost coordinates relative to the current viewable area. This will be (0, 0) when the page isn’t scrolled at all.

    We’ll also have to size the element to have it span the whole viewable area of the browser.

    These two things will make sure that no matter where we have scrolled in a page and whatever be the window size, this black overlay element always covers the current viewport.

  2. 2. Content Box: A nicely styled box with a close button is all we need. We’ll place it at the center of the screen. Since we have calculated the topmost and leftmost coordinates relative to the current viewport and we also have the current viewport’s dimension, we can easily position this at the center, no brainer! We’ll give this a z-index larger than the black overlay element such that this is at the top of everything.

    Besides this, we’ll also have to take care that these two elements move along with the page in case user tries to scroll the page when the our lightbox is open. This will make sure that (1) black overlay element always fills the screen (2) content box is always at the center.

Sounds pretty simple? Well, it is! It’ll call this Blackbox, you may call it whatever you feel like. Here is the code (Demo here):


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Blackbox - A very simple Lightbox clone</title>

<script type="text/javascript">
/*
 * Script: Blackbox (very simple Lightbox clone)
 * Author: Arvind Gupta (contact@arvindgupta.co.in)
 * Date: 14-Nov-09
 * Copyright: 2009 Arvind Gupta

 *            You may freely use this script wherever
 *         you want and in whatever way you wish
 *         but please don't remove this note.
 *
 */

// OBJECTS

// Black overlay element
var darkbox;
// Content box
var content;

// FUNCTIONS
function init()
{
   // Set "onScroll" event handler

   window.onscroll = scroll_box;
}

function open()
{
   // Create elements
   darkbox = document.createElement('div');
   content = document.createElement('div');

   // Style them with the existing ids
   darkbox.id = 'darkbox';
   content.id = 'content';

   // FILL CONTENT BOX

   // Have the close button
   content.innerHTML = '<a style="position: absolute; top: -30px; right: -30px; text-decoration: none;" href="javascript:close();"><img style="border: none;" src="fancy_closebox.png" /></a>';
   // The main content

   content.innerHTML += '<div id="main_content"><h1>Hello</h1><p>Hello World!<br /> How is this looking?</p></div>';

   // Add these elements to the body

   document.body.appendChild(darkbox);
   document.body.appendChild(content);

   // Calciulate coordinates and such
   var pos_top = document.documentElement.scrollTop
   var pos_left = document.documentElement.scrollLeft;
   var screen_width = document.documentElement.clientWidth;
   var screen_height = document.documentElement.clientHeight;

   // Place the "darkbox" element and give it the size

   darkbox.style.top = pos_top + 'px';
   darkbox.style.left = pos_left + 'px';
   darkbox.style.height = screen_height + 'px';
   darkbox.style.width = screen_width + 'px';

   // Now place the content box at the center
   content.style.left = (pos_left + (screen_width / 2.0) - (content.offsetWidth / 2.0)) + 'px';
   content.style.top = (pos_top + (screen_height / 2.0) - (content.offsetHeight / 2.0)) + 'px';
}


function scroll_box ()
{
   // If "Darkbox" open
   if(darkbox != null)
   {
      // Find new topmost, leftmost position w.r.t the current viewport
      // Also find new window size

      var pos_top = document.documentElement.scrollTop
      var pos_left = document.documentElement.scrollLeft;
      var screen_width = document.documentElement.clientWidth;
      var screen_height = document.documentElement.clientHeight;

      // Positions elements accordingly
      darkbox.style.top = pos_top + 'px';
      darkbox.style.left = pos_left + 'px';
      darkbox.style.height = screen_height + 'px';
      darkbox.style.width = screen_width + 'px';

      content.style.left = (pos_left + (screen_width / 2.0) - (content.offsetWidth / 2.0)) + 'px';
      content.style.top = (pos_top + (screen_height / 2.0) - (content.offsetHeight / 2.0)) + 'px';
   }
}


function close()
{
   // Delete elements
   document.body.removeChild(darkbox);
   document.body.removeChild(content);
}
</script>

<style>
#darkbox {
   position: absolute;
   top: 0px;
   left: 0px;
   opacity: 0.6;
   filter:alpha(opacity=60);
   background: #000;
}

#content {
   position: absolute;
   z-index: 1001;
   background: #fff;
   border: 10px solid #000;
   width: 500px;
   height: 300px;
}
#content #main_content {
   overflow: auto;
   width: 500px;
   height: 300px;
}

</style>
</head>

<body onload="init();">
<a href="javascript:open()">Open Box</a>
</body>
</html>

Related Posts:

Popular posts from this blog

The Best Way(s) to Comment out PHP/HTML Code

PHP supports various styles of comments. Please check the following example: <?php // Single line comment code (); # Single line Comment code2 (); /* Multi Line comment code(); The code inside doesn't run */ // /* This doesn NOT start a multi-line comment block /* Multi line comment block The following line still ends the multi-line comment block //*/ The " # " comment style, though, is rarely used. Do note, in the example, that anything (even a multi-block comment /* ) after a " // " or " # " is a comment, and /* */ around any single-line comment overrides it. This information will come in handy when we learn about some neat tricks next. Comment out PHP Code Blocks Check the following code <?php //* Toggle line if ( 1 ) {      // } else {   ...

How to Create an HTML Form Linked with MySQL Database in PHP

If you're looking for example code and detailed discussion on how to create an HTML form that stores data in a MySQL database using PHP then this post might be what you're looking for. I assume that you're familiar with basic HTML, CSS, PHP coding, and  MySQL. I am going to divide this small project into two parts: The HTML form itself that takes input from the user and the PHP script that saves it into the database A table that displays the user-added data that has been saved in the database. We'll be dealing with the first part in this tutorial. Again I'd like to break this problem into a few parts so that it's easier for you to understand and probably gives you an insight into how breaking up a problem into smaller chunks can help make things clearer in your mind. Let's think about it, there is an HTML form (that is HTML code), then there is the PHP code that deals with the user-input data, and the MySQL database itself. For this tutorial, we'll b...

Fix For Toshiba Satellite "RTC Battery is Low" Error (with Pictures)

RTC Battery is Low Error on a Toshiba Satellite laptop "RTC Battery is Low..." An error message flashing while you try to boot your laptop is enough to panic many people. But worry not! "RTC Battery" stands for Real-Time Clock battery which almost all laptops and PCs have on their motherboard to power the clock and sometimes to also keep the CMOS settings from getting erased while the system is switched off.  It is not uncommon for these batteries to last for years before requiring a replacement as the clock consumes very less power. And contrary to what some people tell you - they are not rechargeable or getting charged while your computer or laptop is running. In this article, we'll learn everything about RTC batteries and how to fix the error on your Toshiba Satellite laptop. What is an RTC Battery? RTC or CMOS batteries are small coin-shaped lithium batteries with a 3-volts output. Most laptops use ...