Monday, October 13, 2014

Creating a jQuery popup with an overlay


Create a basic popup and overlay with minimal styling and without any additional settings using jQuery/HTML and CSS.


Creating Overlay using HTML and CSS : 
Overlay is a container with some translucent background color which cover the whole page and user is unable to click on any functional part of the site below it.

HTML
<div id="overlay"></div>

CSS
#overlay {
 display:none; /*hidden on pageload*/
 position:fixed; /*this will disable it from scrolling*/
 width:100%; /*this will give the full width*/
 height:100%; /*this will give the full height*/
 z-index:999; /*this will keep it above all elements in the page*/
 left:0; /*this will align it to the left*/
 top:0; /*this will align it to the top*/
 background:#000; /*this will give it a black background*/
}

Creating Popup using HTML and CSS : 

HMTL
<div class="popup" id="popup1">
<a href="#" class="close">X</a>
<p>
this is a demo popup
</p>
</div>

CSS
.popup {
 display:none; /*hidden on pageload*/
 width:200px; /*width of popup*/
 height:200px;  /*height of popup*/
 padding:10px; /*padding for popup*/
 background:#fff; /*background of popup*/
 border:1px solid #000; /*border of popup*/
 position:absolute; /*this will keep it relative to the body*/
 z-index:9999; /*this will keep it above the overlay*/
 top:50%; /*keep popup in center*/
 left:50%; /*keep popup in center*/
 margin-left:-110px; /*keep popup in center (it is the - total width / 2)*/
 margin-top:-110px; /*keep popup in center (it is the - total height / 2)*/
}
.popup .close { /* close link*/
 float:right;
 color:#000;
 text-decoration:none;/*remove underline from the close link*/
}
.popup p { /*popup text*/
 padding:10px 0;
}

Creating button to trigger the popup with overlay :
<a href="#" class="displayPopup">Display Popup</a>

Creating Functionality using jQuery: 
$(function() { //document ready
    $(".displayPopup").on("click", function() { //click event of the button
        $("#overlay").fadeTo(100, .3); //this will show the overlay awith a crossbrowser transparency
        $("#popup1").show(); // show popup1
        return false; //disable event propogation (avoid addition of "#" to url)
    })

    $(".popup .close").on("click", function() { //click event of the close button in popup
        $("#overlay").hide(); //hide overlay
        $(".popup").hide(); //hide popup
        return false; //disable event propogation (avoid addition of "#" to url)
    })
})

Download code files
Related Posts Plugin for WordPress, Blogger...

Receive all updates via Facebook. Just Click the Like Button Below

You can also receive Free Email Updates: