SimpleModal

v1.0.1

Deprecated: please see the current version.

Summary

SimpleModal is a lightweight jQuery plugin that provides a simple interface to create a modal dialog.

The goal of SimpleModal is to provide developers with a cross-browser overlay and container that will be populated with content provided to SimpleModal.

Demo

Download

Support

Usage

As a jQuery chained function, where content is a jQuery object:

content.modal([settings]);

As a stand-alone jQuery function, where content is a jQuery object, a DOM element, or a plain string (which can contain HTML):

$.modal(content, [settings]);

Styling

  • Other than dealing with some IE issues, SimpleModal does not apply styling to any of the elements. modalCloseImg is the only internally defined CSS class, used to style the built-in close icon.
Sample CSS, using default values
#modalOverlay {
  height:100%; 
  width:100%;
  position:fixed; 
  left:0;
  top:0;
  z-index:3000;
  background-color:#000;
  cursor:wait;
}

#modalContainer {
  height:400px; 
  width:600px; 
  position:fixed; 
  left:50%; 
  top:15%; 
  margin-left:-300px; 
  z-index:3100; 
  background-color:#fff; 
  border:3px solid #ccc;
}

#modalContainer a.modalCloseImg {
  background:url(../img/x.png) no-repeat; 
  width:25px; 
  height:29px; 
  display:inline; 
  z-index:3200; 
  position:absolute; 
  top:-14px; 
  left:588px; 
  cursor:pointer;
}
  • For IE 6, the following will handle the PNG used for a.modalCloseImg and fixed positioning for the container and IFRAME:
<!--[if lt IE 7]>
<style type='text/css'>
  body {
    width:100%;
    height:100%;
    padding:0;
    margin:0;
  }
  #modalContainer a.modalCloseImg{
    background:none; 
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
        enabled=true, src='img/x.png',sizingMethod='scale'
      );
  }
  #modalContainer {
    position: absolute; 
    top: expression((document.documentElement.scrollTop 
        || document.body.scrollTop) + Math.round(15 * 
        (document.documentElement.offsetHeight 
        || document.body.clientHeight) / 100) + 'px');
  }
  #modalIframe {
    z-index:1000; 
    position:absolute; 
    width:100%; 
    height:100%; 
    top:0; 
    left:0;
  }
</style>
<![endif]-->

Settings

Both of the functions above accept an optional settings object, which can contain any/all of the following (default value):

  • overlay: (50) The opacity value, from 0 – 100. 0 = transparent 100 = opaque
  • overlayId: (‘modalOverlay’) The DOM element id for the overlay div
  • containerId: (‘modalContainer’) The DOM element id for the container div
  • iframeId: (‘modalIframe’) The DOM element id for the iframe (IE 6)
  • close: (true) Show the default window close icon? Uses CSS class modalCloseImg
  • closeTitle: (‘Close’) The title value of the default close link. Used if close == true
  • closeClass: (‘modalClose’) The CSS class used to bind to the close event
  • cloneContent: (true) If true, SimpleModal will clone the content element
  • onOpen: (null) The callback function called in place of SimpleModal’s open function
  • onShow: (null) The callback function called after the modal dialog has opened
  • onClose: (null) The callback function called in place of SimpleModal’s close function

Callbacks

The callback functions are called using the JavaScript apply function. One parameter, the dialog object, is sent, which contains the overlay, container, content and iframe objects. In addition, inside the callback, this will refer to the SimpleModal object. This will allow you to call the close function, among other things.

  • onOpen: Useful for adding effects to the opening of the modal dialog elements. Your callback function will be passed an object that contains the overlay, container, content, and iframe (for IE6) elements. SimpleModal will handle “showing” the iframe, if necessary.
Example
content.modal({onOpen: function (dialog) {
  dialog.overlay.fadeIn('slow', function () {
    dialog.container.slideDown('slow', function () {
      dialog.content.fadeIn('slow'); // See Other Notes below regarding
                                     // content display property and
                                     // iframe details
    });
  });
  • onShow: Useful for binding events or any other actions you might want to perform after the modal dialog elements have been displayed. Your callback function will be passed an object that contains the overlay, container, content, and iframe (for IE6) elements.
  • onClose: Useful for adding effects to the closing of the modal dialog elements. Your callback function will be passed an object that contains the overlay, container, content, and iframe (for IE6) elements. $.modal.remove(dialog); can be called to remove all of the elements, or you will need to remove them manually. Example: dialog.content.remove();, etc.
Example
content.modal({onClose: function (dialog) {
  dialog.content.fadeOut('slow', function () {
    dialog.container.slideUp('slow', function () {
      dialog.overlay.fadeOut('slow', function () {
        $.modal.remove(dialog); // must call this to remove
                                // the elements from the DOM
                                // or remove the elements manually
      });
    });
  });
}});

Other Notes

iframe
  • For IE6, SimpleModal handles the creation and removal of an iframe, which is needed to prevent select options from bleeding through the modal dialog. If you use an onClose callback, see onClose in the Callback section above.
Content CSS display Property
  • If you use an onOpen callback, the dialog.content display value will be the same as what was passed in to SimpleModal. So, if you want to use an effect on the dialog.content and the element is not set to display:none, you’ll have to call dialog.content.hide(); first, before you call your open effects.
Cloning and Element Removal
  • By default, SimpleModal will clone the content element that you pass in. In the close function, when cloneContent is true, SimpleModal will “remove” the element, otherwise it will just “hide” it. If you use an onClose callback, you’ll have to deal with removing vs hiding the content element.
  • SimpleModal always removes the overlay, container and iframe elements when closed. If you use an onClose callback, see onClose in the Callback section above.
Browser Compatibility

SimpleModal has been tested in the following browsers:

  • IE 6, 7
  • Firefox 2
  • Opera 9
  • Safari 3

29 thoughts on “SimpleModal”

  1. Giving it a look as well. Not a fan of the thickbox, limits me too much for what I need to do. Want something flexible. But looking at your documentation this looks cool.

  2. Eric, Thanks for simplemodal, it’s totally gorgeous and easy to implement. However… the fact that the modal window clones the content by default really led me in circles for quite a while.. is there a reason you chose this behavior? Anyway, now that I’ve finally realized that I’m dealing with cloned data, I can fix all my event handlers. Phew.. that took some work!

  3. @Mike / @Morgan – Thanks! I hope you both found uses for SimpleModal.

    @Paul – I’m sorry the cloning caused you issues πŸ™ When I created SimpleModal, all of the content I was dealing with needed to be cloned, so that is why the default for cloneContent is true πŸ˜‰ .

  4. Also the script is deleting the this.dialog.content even if the content is NOT cloned, which makes opening the lightbox a second time present an issue.. πŸ™‚

  5. Nice plugin, finally a modal that’s easy to understand and use!

    I wanted to point out that you could clone event handlers as well, by simply changing…

    this.dialog.content = this.opts.cloneContent ? content.clone() : content;
    

    to

    this.dialog.content = this.opts.cloneContent ? content.clone(true) : content;
    

    (I believe that’s on line 148)

    That worked out just fine for me… and allowed me to add a “cancel” button, something like this:

    $(document).ready(function(){
        $('.dialog input[value="cancel"]').click(function(e){
            e.preventDefault();
            x.close();
        });
        $('.edit').click(function (e) {
          d = $(this).attr('id').substr(1);
          e.preventDefault();
          x = $('#d' + d).modal();
        });
    });
    
  6. Pingback: SimpleModal - Mostrar dialogos con jQuery β€” AJAX β€” Freak Group — DiseΓ±o web, recursos y mucho mΓ‘s

  7. Thanks for creating the project! I looked at several different solutions (blockUI, jqModal, lightbox, and thickbox) and ended up finding your solution easy and flexible!

    FYI to others wanting another way to close the modal, adding the following code to the bindEvents section will allow users to click on the overlay and have the modal close (if you like me and didn’t want to use the close button).

    $('#' + this.opts.overlayId).click(function (e) {
      e.preventDefault();
      modal.close();
    });

    Make sure to unbind as well:

    $('#' + this.opts.overlayId).unbind('click');
  8. Hi, can Flash content be used inside the modal div? I tried it with no luck using script for active content (AC_RunActiveContent.js) and without it.

  9. @Tony – I just tried it out using sample files from Adobe and was able to get it working. I had to adjust the z-index of the div that contains the Flash content, which is probably the issue you are having. I set the z-index to 5000.

    Try that out and if you still have issues, let me know.

  10. In the contact form example how could the pressing of the “enter” key within the Name field be detected to then run the .click() for the .send image? I know a function could be called via onkeypress on the Name field to grab the event but am unsure how that function could then trigger that someone is trying to send the contact form but the validation and everything else needs to be ran.

    I realize that someone more than likely would not be pressing the enter key in that example but seemed like if I could see how to do it in the example then I could apply it to what I am trying to build. I am using the SimpleModal to present my users with an LDAP search/results screen so they can find a user, select the user and have that user’s UID put into the main form.

  11. alright, ive tried to re-write it, but is there a way to make a link call the function? like a <a href=”javascript:w/e()
    instead of the input area.
    and can this be used withing a table, because whenever i place the div and input in a table it is clickable, but nothing happens.

  12. @Aaron Rouse –
    Here’s a way to bind the enter key:

    $('#contactModalContainer #name').bind('keypress', function (e) {
    	if (e.keyCode == 13) {
    		$('#contactModalContainer .send').trigger('click');
    	}
    });
    

    Place this code in the show: function (dialog) { ... } block, after the $('#contactModalContainer .send').click(function (e) { ... } block.

    If you have any issues, let me know.

    @Richard –
    Are you trying to use one of the demo’s or just the plugin? I’m not sure what you mean by “can this be used within a table”. You can email me the code you are trying to use and I’ll see if I can help.

  13. ok do you have AIM? thats the best way to contact me.
    and yes im using the contact modal from the demo, but if i place the div and the input that calls the modal, and its put inside a table, which is basically my whole website, its is clickable, but nothing happens, not even any errors.

  14. I was wondering if anyone out there has implemented this as a plugin for WordPress? I’ve been banging my head against a wall all day and think someone with more skills using JQuery may have already done some leg work on this.

    Thanks in advance for any help

  15. Eric,

    Thanks for the code, when I place that into your example form it seems to work as expected in both IE and FireFox. For some reason though the test code I am working on, it does not function 100%.

    On mine in Firefox if I type a character and hit the backspace then press enter I get the message about the field being required. If I type in some search criteria it begins to search but the closes out, happens that way in IE and Firefox. I copied the code up into a temp directory on my site so that you could see it:

    https://www.happyhacker.com/demo/index.html

    A search criteria that would return something would be: Rouse

    The other issue I will need to address that I have not is how to trigger a click on the Close button. Once a user has been selected I want it to populate their UID into the main page and close out the Modal. I will also need to figure out how to integrate it into existing forms, when I first put up the test code I got some odd display behavior in IE7 so for a temp solution I just slimmed down your demo page for testing purposes.

  16. I have a .NET page (PAGE ONE – for simplicity) with a form and many many fields and buttons.
    When the user clicks a particular button (LOAD BUTTON) I want to open a modal overlay window that asks for the record number the user wish to load.

    So I already have FORM tags in PAGE ONE. All I want to do is opening a window with a text box and an OK button and finally post back to PAGE ONE once the user clicks on the OK button. Can this be done using this module you have created? I am confused by the fact you load an HTML snippet through AJAX (I don’t need to do this, right?) that contains FORM tags (I cannot do this since I already have form tags on my page, right?)

    Any help would be really appreciated

  17. Hi Eric, thanks for the code. I’ve one question: how can I close the modal from a page inside an iframe. I’ve tried to write a function to close the modal, but with no success.

    I created a flash movie that is displayed inside the simplemodal through an iframe. When the movie ends, it executes a function to close the simplemodal. But I can`t close this modal.

    There is a easy way to make this?

  18. How to understand these settings in your sample CSS:

    position:fixed;
    left:50%;
    top:15%;
    margin-left:-300px;

    Are you trying to center anything?

  19. @Robin – The WordPress plugin is almost ready. I ended up making some changes to SimpleModal, which has delayed the plugin.

    @Aaron – I also am making some changes to the contact demo. One of those changes is to make the send and cancel images input type=image, so when the enter button is pressed, it will submit the form.

    As for the question about populating the UID and closing the dialog…there are a lot of options. Have you tried using the onClose event to grab the UID, place it in the page, then close the dialog?

    @Francesco – Here is a crude example of what I think you are asking for:
    HTML:

    <a href='#' id='records'>records</a>
    <form id='myForm'>
    </form>

    JavaScript:

    $(document).ready(function () {
      $('#records').click(function (e) {
        e.preventDefault();
    
        var select = $('<select>').attr('name', 'records');
        select.append($('<option>').attr('value', -1).html('Number of Records'));
        
        for (var i = 1; i <= 10; i  ) {
          select.append($('<option>').attr('value', i).html(i));
        }
        
        select.modal({onShow: function (dialog) {
          dialog.data.change(function () {
            if (this.value && this.value > 0) {
              var form = $('#myForm');
    
              for (var i = 1; i <= this.value; i  ) {
                var label = $('<label>').attr('for', 'record_'   1).text('Record '   i   ':');
                var input = $('<input type="text">').attr('id', 'record_'   1).attr('name', 'record_'   i);
                form.append($('<div>').append(label).append(input));
              }
            
            $.modal.close(); // for SimpleModal 1.1
            }
          });
        }});
      });
    });

    @Kan – I’m not really sure πŸ˜‰ If you can email me an example link or code, I could take a look.

    @Bill – Glad you understand…it is a little convoluted =)

  20. Eric, no I have not tried the onClose and actually have not tried anything in regards to the UID because was trying to figure out the odd behavior I was getting with the enter key on my attempt vs. using your code on your contact form example. I will wait for the change you are doing to the contact form then modify my code and making a note to use the onClose. Thanks for the help on this, been a little bit of a struggle for me since new to jQuery at the same time but overall not been too bad of a learning curve.

  21. Hi Eric, Happy New Year.

    Well, I have a flash movie inside an iframe, and this iframe is inside a SimpleModal. Well, I need to call a function that closes the SimpleModal when the flash movie ends.

    I’d tried some codes but I can’t close the SimpleModal from the inside of iframe. Do you have any idea?

    Sorry but my English isn’t good.

  22. @Kan – Happy New Year to you too!

    I think I have an answer for you. I’m not sure what happends when a flash movie ends, but if you can trigger a JavaScript event, the following should close the modal dialog that contains the iframe:

    <script type='text/javscript'>
    function flashEnded() {
        window.parent.jQuery.modal.close(true); // true means it's an external close call
    }
    </script>

Comments are closed.

Scroll to Top