Prettier Alert Messages in OpenSocial Apps

Posted on 18 April 2008 by Johannes Fahrenkrug. Tags: orkut JavaScript Programming jquery OpenSocial
Google has posted the Orkut Developer Guidelines for developers who build OpenSocial applications for the platform. These seem do be very good guidelines in general, not just for OpenSocial and not just for Orkut (although some are very specific to the platform). The first "MUST" item in the user experience section reads:
Always include error handling routines to generate a user-friendly message. HTML alert boxes are strongly discouraged as they're interruptive.
Makes sense. Alert boxes are horrible. So I came up with an easy way to include non-interruptive error messages in my OpenSocial application. This is no rocket science at all and there are lots of different and most likely better ways to do this, but I want to share this with you anyway because it might be helpful to someone. So here we go:
  1. I use jQuery for some JavaScript luxury. Include the libraries in the html section of your gadget xml:
    <script src="http://YOURSERVER/jquery/jquery-1.2.3.min.js" type="text/javascript"></script>
    
  2. Include this somewhere in the html section of your gadget xml where you want the error messages to appear:
    <div style="text-align: center; width: 80%;">
    <div id="error-msg-box" style="display: none;">
    <p><!-- msg goes here --></p>
    <input onclick="dismissError()" value="OK" type="button">
    </div>
    </div>
    
    Style it to your liking. I'm not a designer, so please don't ask me ;-). This is the style I used for the inner error-msg-box:
    padding: 3px; border: 2px solid #BB0000; color: #BB0000; width: 100%; text-align: center;
    See what I mean?
  3. Now just add these two functions to your JavaScript:
    /**
      Shows an error on the top of the page
      @see #dismissError
    */
    function showError(msg) {
      $('#error-msg-box > p').html(msg);
      $('#error-msg-box').show('normal', function() {gadgets.window.adjustHeight();});
    }
    
    /**
      Dismisses the error on the top of the page
      @see #showError
    */
    function dismissError() {
      $('#error-msg-box').hide('normal', function() {gadgets.window.adjustHeight();});
    }
    
  4. That's it. Now you can call
    showError('Something went wrong!');
    
    From anywhere in your code and the user can click Dismiss to dismiss the message. You can also dismiss the message programatically by calling
    dismissError();
    
    from your code.
This even honors the second "MUST" of the User Experience section:
Always call the gadgets.window.adjustHeight() method when the application's content changes to prevent scrollbars from appearing.
Enjoy.

Comments

Please keep it clean, everybody. Comments with profanity will be deleted.

blog comments powered by Disqus