enavu webdevmania tutsvalley psdestination
visit the enavu network
33 Comments Article Title Overlay Article Title

How to make a completely reusable jquery modal window

In this tutorial we will code a modal window with jQuery that is completely reusable, so we can put multiple modal windows without making a specific coding for it.

DZoneDiggDesign FloatDeliciousBlinklistRedditFacebookGoogle BuzzTwitterStumbleUponTumblrShare

Demo     Source

HTML


    <center><h1>Modal Window Demo</h1></center>

    <p><a class='activate_modal' name='first_window' href='#'>First modal window.</a></p>
    <p><a class='activate_modal' name='second_window' href='#'>Second modal window.</a></p>

    <div id='mask' class='close_modal'></div>

    <div id='first_window' class='modal_window'>This is the first modal window</div>
    <div id='second_window' class='modal_window'>Welcome to the second modal window</div>

Quite easy, we have an element that will trigger the specific modal window. We are getting the modal window id from the name attribute of the trigger element. It’s importnat that the mask goes after the normal content and after the mask we have our modal window(s).

CSS

        #mask{
        position:absolute; /* important */
        top:0px; /* start from top */
        left:0px; /* start from left */
        height:100%; /* cover the whole page */
        width:100%;  /* cover the whole page */
        display:none; /* don't show it '*/

        /* styling bellow */
        background-color: black;
    }

    .modal_window{
        position:absolute; /* important so we can position it on center later */
        display:none; /* don't show it */

        /* styling bellow */
        color:white;
    }

    /* style a specific modal window  */
    #modal_window{
        padding:50px;
        border:1px solid gray;
        background: #246493;
        color:black;
    }

JQuery

    $(document).ready(function(){

    //get the height and width of the page
    var window_width = $(window).width();
    var window_height = $(window).height();

    //vertical and horizontal centering of modal window(s)
    /*we will use each function so if we have more then 1
    modal window we center them all*/
    $('.modal_window').each(function(){

        //get the height and width of the modal
        var modal_height = $(this).outerHeight();
        var modal_width = $(this).outerWidth();

        //calculate top and left offset needed for centering
        var top = (window_height-modal_height)/2;
        var left = (window_width-modal_width)/2;

        //apply new top and left css values
        $(this).css({'top' : top , 'left' : left});

    });

        $('.activate_modal').click(function(){

              //get the id of the modal window stored in the name of the activating element
              var modal_id = $(this).attr('name');

              //use the function to show it
              show_modal(modal_id);

        });

        $('.close_modal').click(function(){

            //use the function to close it
            close_modal();

        });

    });

    //THE FUNCTIONS

    function close_modal(){

        //hide the mask
        $('#mask').fadeOut(500);

        //hide modal window(s)
        $('.modal_window').fadeOut(500);

    }
    function show_modal(modal_id){

        //set display to block and opacity to 0 so we can use fadeTo
        $('#mask').css({ 'display' : 'block', opacity : 0});

        //fade in the mask to opacity 0.8
        $('#mask').fadeTo(500,0.8);

         //show the modal window
        $('#'+modal_id).fadeIn(500);

    }

Final words

And that’s it. We made a modal window function with jquery we can easily use for multiple modal windows on the same page. Also what’s important is that you can trigger the modal window with any elements, just put class “activate_modal” to it and name attribute that fits the ID attribute of the modal window.

Related posts:

  1. Top 10 jQuery Modal Box Plugins
  2. Daily Tip : Difference between $(document).ready and $(window).load in jQuery
  3. Simple Fast and Dirty Introduction to jQuery
  4. Making image captions using jQuery
  5. Easy Unobstructive jQuery Print Page Tutorial

Slobodan Kustrimovic

This author has yet to fill his BIO.

Did you absolutely LOVE this article... share it!

Comments

  • great! i’m using it in one of my little projects: http://www.demianvillanueva.com/demas/lourdes_leoz/contacto.html (Postal image / Map image)

    I have a issue in IE6, but is yet usable.
    In IE7 – FF – Safari works great !

    thanks for share !

  • Glad to hear it’s useful :) What’s the IE6 issue. I’m having some problems with my IE tester, can’t check it at the moment.

  • a screenshot: http://is.gd/3Jyoz

    The issue is with the position of the “mask” (which don’t cover the entire window) and of course the close-event with click(function() on it…

    I have to click twice that mask div on top-right to close the modal window. Like I said, it’s yet usable

  • well.. I couldn’t find the “optimun” solution to resolve the bug that i’ve mention before, but a nice and functional one.

    I’ve just added a “close button” on top-right corner with “.close_modal” class…. Like my modal window show an image, I also added “.close_modal” class to it, so user can close the modal windows clicking on mask, close button and the image itself.

    demo of what I said: http://www.demianvillanueva.com/demas/lourdes_leoz/contacto.html

  • Try this

    after:

    //get the height and width of the page
    var window_width = $(window).width();
    var window_height = $(window).height();

    put:

    var document_height = $(document).height();
    $(‘#mask’).css({ ‘width’ : window_width, ‘height’ : document_height });

    And tell me if that fixes it :)

  • great! your code solve the problem !
    Thanks boba, now the “mask” it works in IE6 ! Good update!

    Also, i’m gonna try to solve the -all browsers- problem when you scroll the page, the “mask” it’s not dymanic…it doesn’t overlay the entire windows when scroll or resize the window.

  • with the previous fix it should be completely covering the whole page.

    Maybe the css part is interfering with it. Remove the height and width attributes from the #mask in CSS. That should fix it, and it will be cross browser :)

  • The tutorial is great~ thanks a lot!

    but one more thing i wanna know,
    if i resize the browser, how can it be keep in center.

  • @David Mak – Here is a temporary solution, i’ll update the tutorial in few days with that feature.

    $(window).resize(function(){
    //get the height and width of the page
    window_width = $(window).width();
    window_height = $(window).height();

    //get the height and width of the modal
    $(‘.modal_window’).each(function(){

    //get the height and width of the modal
    var modal_height = $(this).outerHeight();
    var modal_width = $(this).outerWidth();

    //calculate top and left offset needed for centering
    var top = (window_height-modal_height)/2;
    var left = (window_width-modal_width)/2;

    //apply new top and left css values
    $(this).css({‘top’ : top , ‘left’ : left});

    });

    });

    Didn’t test but should work without a problem.

  • hi Boba, thank you for your useful solution!~

  • Hi Boba

    Thank you for this guide.

    I am putting an iFrame into the modal window but on the same page I do not want to put it in the div and Iframe 118 times so is there a way where the src in the iFrame is ” + source + ” so then it can be picked up from the tag.

  • Wsp Boba! Tnx Bro!

  • really nice tutorial. thanks.

  • Great tutorial, I been looking for a lightweight Modal, all the jquery ones are bulky and this is perfect! I hope you continue to improve it =)

  • @Jason – Glad you like it :)

  • Hello! world
    I am looking for a comment box like this one.
    please let me know if you can help me
    thanks.

  • @ossie – Hello. Comment box like this one? Don’t understand what you need.

  • Hello!! Boba
    I am looking for a comment box script like this one. so visitor can leave comment about my website.
    just like this one so visitors like me leave a comment about your site.

    Thanks very much if can help me.

    Ossie

  • You can check out this commenting system.

  • i don’t know how write the jquery.
    Can person help me?

  • I would suggest watching the jQuery for absolute begginers screencast series. 30% of what i know now i learned in those few hours of screencasts :)

  • Very thanks Boba:)

  • @RBence – Don’t mention it, glad to help. :)

  • This is a great find. I was looking for something else but found this solution instead… will definitely implement it. This saves the trouble of having to name a lot of divs and form elements and attaching events to each a#openwindow1, a#openwindow2… Thanks!

  • Hi There, great solution and thanks for it, I´m try to understand it, because I´m new at this (Web Programming).

    I want to know how can I call a different page with a link?? (I don´t want to have the divs in the same page)

    Many Thanks!!

  • hi, i got this working partially in my site… unfortunately, after adding the first patch:

    code:
    var document_height = $(document).height();
    $(‘#mask’).css({ ‘width’ : window_width, ‘height’ : document_height });”

    the popup and mask won’t work…
    without it, it works fine except for the mask that doesn’t fill all.. :(

    is there a new update on this module?
    thanks :D

  • Hey John, this should work great :)

    
    
    

  • Dude great job! This is awesome, love how you commentated everything! I’m learning jQuery and this is the best for learning!

  • Having issue with the mask not filling the whole of the page. The site is written in VB.net using master template page and everything goes inside a form.

    Divs are used to layout the page however I think the stacking order is having an effect on this.

    The top and left of the mask is taking the top and left from the main content div and not the actual document if you see what I mean.

    I tried another well known solution for overlay modals and got a similar problem because of the staking issues. This time though it was to do with the mask overlaying everything including the modal box which should be active.

    Is there a wy around that I can force the mask to work at form level and not sub division level?

    if I put the code within the master templates then it works because the mask are outside the form so they can reference each other. The form seems to be the big issue here.

    Any help is really appreciated.

    TIA

    Mick

  • Hey Mick,

    You will actually have to take the mask and put it outside the form. The form is positioned relatively so the fixed position of the mask doesn’t work when that happens.

  • Thank you very much. Greats

  • What if I want multiple modals where each modal moves “a step” higher and the mask moves to cover it. I got it working with hardcoding some info and then “stepping” the z-index 10 points up and down, but I couldn’t come up with a good way to do this dynamically so I could put it on a master page and have all other pages be able to use it.

    Any suggestions?

    Thanks in advance.

Leave your own!

Sponsors

freedcamp free project management

Popular Articles

fzilla file hosting