Easy way to use jQuery modal windows

30 Jan

I’m working on a social network project at this moment, I’m taking care of creating some  javascript (jQuery) + HTML + CSS components so the developers can use all those components without knowing why or how they work. One of the needs was to be able to create modal windows for warnings or even forms.

Eric Martin created this great modal jQuery plugin wich I’m not willing to compete with, so what I created is a jQuery plugin that uses the Simple Modal plugin but adds one functionality. The idea is to configure a simple modal activation without using any javascript, to do that all we have to do is adding two classes to the desired link (or any other clickable elements).

How to use:

  1. Link the needed Javascripts (jquery.js, jquery.simplemodal.js, jquery.modalcontrol.js).
  2. Activate the plugin for a container.
  3. Add the two classes to the desired link (“modal” and “modalContainer_” + elements id).

Let’s create a simple example step by step.

1. Link the needed Javascripts

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.simplemodal.js" type="text/javascript"></script>
<script src="js/jquery.modalcontrol.js" type="text/javascript"></script>

2. Activate the plugin for a container

To activate the plugin we are going to bind a function for the document load event. Inside the function we are going to activate the plugin for a container (it will find all links inside the container) or directly to a specific link.

$(document).ready(function(){
	$('#container').modalControl();
});

3. Add the classes to links

This is the cool part, once we have the first steps done we don’t need to look at javascript when we need to open new modal windows on our web site or application.

<div id="container">
	<a href="#" class="modal modalContainer_content">Open modal</a>
	<div id="content" style="display:none">
		<h2>Modal window</h2>
		<p>This is the content of our modal window</p>
	</div>
</div>

That’s it, the script will search for all elements with the class “modal” inside the container and bind a click event to open the related content on a modal window

For those who are interested in the codding, please check the unit testing for the modal control script.

Download jquery.modalcontrol.js

One Response to “Easy way to use jQuery modal windows”

  1. Demitry 22. Feb, 2012 at 3:41 pm #

    Just found this, will try when I get home. Seems awesome though, simplest solution I’ve found thus far. Thanks!

Leave a Reply