Quantcast
Channel: Web Developer Source
Viewing all articles
Browse latest Browse all 12

How to Do Simple Model Window using jQuery

$
0
0

In this example, how to create a simple modal window with JQuery.

1. HTML code and A tag attributes


Simple Modal Window
 
Testing of Modal Window | Close it

2.CSS Style sheet Code


3. Javascript


It’s very straight forward and easy to understand. Remember, you need to include jQuery framework.

Download

4.Launch modal window with Javascript

Due to popular demand :) , I have an example for it. The concept is simple. I wrapped the modal window script inside a function, and then you will able to call the modal window using javascript function call.
Yes, you will able to load the modal window on page load as well :)

$(document).ready(function () {
  //id is the ID for the DIV you want to display it as modal window
  launchWindow(id);
});

View Demo

And, if you want to close the modal window on key press, any keys you want, you can add the following function.

$(document).keyup(function(e) {
  if(e.keyCode == 13) {
    $('#mask').hide();
    $('.window').hide();
  }
});

Use Cookie on First Load

Another popular demand from readers and this is how you do it. You need two functions (createCookie and readCookie) from this post about web cookies

$(document).ready(function() {
//if the cookie hasLaunch is not set, then show the modal window
if (!readCookie('hasLaunch')) {
    //launch it
    launchWindow('#dialog1');      
    //then set the cookie, so next time the modal won't be displaying again.
    createCookie('hasLaunch', 1, 365);
}
 
});

View Demo

Recalculate the Position of Modal window and mask on window resize

Don’t know how I missed it, this is the code that reposition the modal window and recalculate the dimension of mask if user resized the windows.

$(document).ready(function () {
$(window).resize(function () {
  
        var box = $('#boxes .window');
  
        //Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
       
        //Set height and width to mask to fill up the whole screen
        $('#mask').css({'width':maskWidth,'height':maskHeight});
                
        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();
  
        //Set the popup window to center
        box.css('top',  winH/2 - box.height()/2);
        box.css('left', winW/2 - box.width()/2);
  
});
 
});

Source: http://www.queness.com


Viewing all articles
Browse latest Browse all 12

Trending Articles