Going modal

Posted in jabbascript, rails by elisehuard on December 21, 2008

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):
    <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):
    <div id="openWindowHere" class="jqmWindow"></div>
  • then, the script itself, wonderfully simple, to be loaded when the document is ready (see jQuery manuals):
      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.

Tagged with: , ,

One Response

Subscribe to comments with RSS.

  1. p8 said, on December 18, 2009 at 3:02 pm

    Thanks for the example!
    I had some trouble implementing it because you’re using
    #openWindowHere for the modal div
    #openFormHere for jqm function

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: