How to create Javascript and CSS popup with Lightbox effect

This tutorial helps you to create an lightbox effect using css.

HTML

<a href="#" onclick="lightbox_open();">Open lightbox</a>
<div id="light"></div>
<div id="fade" onClick="lightbox_close();"></div>

The link with onclick attribute launches the popup window.

Fade is the background layer for the lightbox what makes the whole window dark.

Light is the container where you can place your HTML code, text, image anything you want to display.

 Javascript

window.document.onkeydown = function (e)
{
    if (!e){
        e = event;
    }
    if (e.keyCode == 27){
        lightbox_close();
    }
}

Checkes if any key pressed. If ESC key pressed it calls the lightbox_close() function.

function lightbox_open(){
    window.scrollTo(0,0);
    document.getElementById('light').style.display='block';
    document.getElementById('fade').style.display='block';  
}

This script makes light and fade divs visible by setting their display properties to block. Also it scrolls  the browser to top of the page to make sure, the popup will be on middle of the screen.

function lightbox_close(){
    document.getElementById('light').style.display='none';
    document.getElementById('fade').style.display='none';
}

This makes light and fade divs invisible by setting their display properties to none.

#fade{
    display: none;
    position: fixed;
    top: 0%;
    left: 0%;
    width: 100%;
    height: 100%;
    background-color: #000;
    z-index:1001;
    -moz-opacity: 0.7;
    opacity:.70;
    filter: alpha(opacity=70);
}
#light{
    display: none;
    position: absolute;
    top: 50%;
    left: 50%;
    width: 300px;
    height: 200px;
    margin-left: -150px;
    margin-top: -100px;                 
    padding: 10px;
    border: 2px solid #FFF;
    background: #CCC;
    z-index:1002;
    overflow:visible;
}

To place light div to middle of the screen, make sure you set margin-left to half of width (300/2=150), and margin-top to half of height (200/2=100).

If you can not see the fade, light divs on your website, try to set a higher z-index. Don’t forget, that light div needs higher z-index than fade to put it on front.

Please follow and like us:



Leave a Comment

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