Ad

Saturday, November 14, 2009

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 scripts 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:

19 comments:

  1. Preee9:28 PM

    How I add an "comment box" on my web site? can u plz help me in getting a code for the same?

    ReplyDelete
  2. Hi Preee,

    What exactly do you mean by "comment box"? Do you mean "Shout box", search for "free shout box" on Google you'll find plenty of them. Those are very easy to use, just register and put the code provided on your page.

    ReplyDelete
  3. Great job! I thought this was like YouTube only technology, I had no idea that it could be done simply like this - excellent post!

    ReplyDelete
  4. Hi caller unknown,

    Thanks!

    ReplyDelete
  5. Hey, U have done great job and ur information about javascript is very helpful.

    http://www.drcsystems.com/

    ReplyDelete
  6. I am looking for a topic like this. Thank you for sharing this informative article.

    ReplyDelete
  7. I think i know what preee means, do you know of any comment/shout boxes that keep the code on your page so that any new comments are cached by google?

    ReplyDelete
  8. 好的開始並不代表會成功,壞的開始並不代表是失敗.......................................................

    ReplyDelete
  9. 永遠不要躊躇伸出你的手。也永遠不要躊躇接受別人伸出的手。.................................................................

    ReplyDelete
  10. you have given the good information about the java script and kindly also do such for the API's of the java.....

    ReplyDelete
  11. wow, it's a cool javascript !

    ReplyDelete
  12. This comment has been removed by a blog administrator.

    ReplyDelete
  13. thanx 4 da tip. anyway what should i use 2 enter this codes. i need clarification.

    ReplyDelete
  14. What software should i use to enter this codes to work.

    ReplyDelete

You are free to comment anything, although you can comment as 'Anonymous' it is strongly recommended that you supply your name. Thank You.

Please don't use abusive language.