Jabberwocky

snicker-snack!

Going Modal

| Comments

Sometimes you have a little detail you’d like the user to specify, but you don’t want to leave the page. That’s when modal windows can come in handy.

Since i’ve now switched to jQuery completely, i’m using a nice jQuery plugin: jqModal

  • first thing is to download the jqModal script and css, and reference them in the head of your page.
  • then, you choose an element in your page that is going to add as trigger, for instance a link (handy if you want to load in a page using ajax):
1
2
3
<a href="/stuff.html" class="openModal">
  Opening modal window
</a>
  • you need a div or span in your page that’s going to be used as placeholder to contain your content (notice the jqmWindow class):
1
2
<div id="openWindowHere" class="jqmWindow">
</div>

`

  • then, the script itself, wonderfully simple, to be loaded when the document is ready (see jQuery manuals):
1
2
3
4
5
$('#openFormHere').jqm({
  trigger: '.openModal',   // class of the trigger
  ajax: '@href',  // load the page your link points to
  overlay: 30  // transparent background to your page - you can adjust that in jqModal.css as well
 });
  • If you want to submit the form with Ajax, you can add a callback function (onLoad:ajaxify for instance) in the previous code. That callback function should then catch the submit event, and make sure the submit is done with Ajax.

In addition to being nice and simple, this also degrades gracefully when javascript is not present. You’re just left with a link to the next page. In Rails, if your modal window contains a form, if you make sure that your format is javascript, you can then adapt the original page using javascript (using a .js.erb template) depending on the response (for instance, i usually insert errors at top of the page, or change the corresponding element – see Ryan Bates’ webcast on jQuery for tips).

In one case, this formula doesn’t cut it: when you’ve got to upload a file. Ajax doesn’t upload file, multipart or no multipart. I’ll give one possible workaround in next post.

Comments