Modal.js updated

Shortest post ever: Just wanted to mention my Modal.js class is still a work-in-progress. Today I made a few updates, most notably to some CSS handling and to the styling of the ‘close’ button (looks much more sophisticated now). Check it out.

Custom modal windows using canvas and MooTools

In my previous post Fun with canvas and MooTools: a Rectangle class, I explained that I wanted to make a modal window for a project at my workplace. I was interested in using MochaUI, but felt it was a bit heavy for my needs. I started playing with the canvas element (using excanvas.js for Internet Explorer support), and wound up making a useful Rectangle class that can quickly draw shapes in canvas using JavaScript.

Shortly afterward I built a simple modal window class named Modal using MooTools. This class combines a dynamic canvas drawing API (the Rectangle class) with dynamic DOM element generation to create on-demand modal windows using no external images. My goal was to make this about as easy to use as a normal JavaScript alert, prompt or confirm window.

I’ve been playing with it over the last week or so, and while it’s nowhere near perfect (esp. the ‘close’ button), I think it’s good enough for my project at work. I figured I’d post it here in case anyone wants to have a look. Feel free to use it if you like, but remember it comes as-is with no warranties! View Modal.js here.

Note: The code in Modal.js is subject to change!

I’m completely open to suggestions for code improvements (my code still feels ‘hacky’ to me), but I’m not really interested in adding new features at the moment. If you really want a full-featured, well-crafted window system, you should use Greg Houston’s MochaUI.

Modal Examples:

The default

The simplest way to invoke the window is:

var modal = new Modal({ title: "My title", html: "<p>My html code goes here</p>" });

Simple no-frills

You have the option of not using a window titlebar or ‘close’ button:

var html = "<p>This is a modal window without any title bar.</p>";

var modal = new Modal({
    html: html,
    width: 300,
    height: 200,
    edgeMargin: 1,
    windowRadius: 9,
    opacity: 0.80,
    colors: {
        modalBackground: "#CCC",
        windowBackground: "#999",
        contentBackground: "#EFEFEF"
   showTitleBar: false

Public Methods

close() This closes the modal window. Once the window is closed, the elements are destroyed and garbage collected using MooTools’ element.destroy method.

var mymodal = new Modal({
    title: "My title",
    html: "<p><a href='#' onclick='return goAway()'>Close me</a></p>"

function goAway(){
    return false;


The options available in the Modal class are:


  • title (String) Text content for titlebar. String format, loads into an h1 element.
  • html (String) Text content for the main window content. Loads into a div.
  • padding (Number, default is 12) Indicates how much padding the content div gets, in pixels.
  • font (String, default is “Verdana, Geneva”) Sets CSS style for the title and window content. Can be overridden by inline styles.
  • fontSize (String, default is “small”) Sets CSS style for the window content div. Can be overridden by inline styles.


  • width (Number, default is 350) Width of window before the drop shadow gets added, in pixels.
  • height (Number, default is 200) Width of window before the drop shadow gets added, in pixels.
  • shadowSize (Number, default is 6) Size of drop shadow, in pixels (note: not 100% pixel perfect measurements).
  • titlebarHeight (Number, default is 28) Size of titlebar, in pixels.
  • edgeMargin (Number, default is 1) Size of window chrome between shadow and content area, in pixels.
  • windowRadius (object OR number) Size of window corner radius, in pixels. If a number is specified, all four corners get the same radius. If an object is used, each corner gets the number specified (see below).
    • windowRadius.topLeft (Number, default is 9)
    • windowRadius.topRight (Number, default is 9)
    • windowRadius.bottomLeft (Number, default is 3)
    • windowRadius.bottomRight (Number, default is 3)


  • animate (Boolean, default is true) Indicates whether or not to fade out the modal background when dismissing the window.
  • backgroundClickDismissesModal (Boolean, default is true) Indicates whether or not clicking the background will dismiss the modal window.
  • closeButton (Boolean, default is true) Indicates whether or not to include a close button. Only works when showTitleBar is also set to true.
  • showTitleBar (Boolean, default is true) Indicates whether or not the title bar should be rendered.


  • opacity (Number, default is 0.66) Indicates the opacity level of the background modal div. Number must be between 0 and 1.
  • colors (object) Child properties are used to specify colors for window elements. All color parameters accept standard CSS color conventions, including hex and RGB.
    • colors.modalBackground (Default is #000) Background modal div.
    • colors.windowBackground (Default is #AAA) Window chrome color.
    • colors.windowTitleBar (object) Used to create a gradient background for the window’s title bar. Accepts two properties: top and bottom.
      • (Default is “#F5F5F5”)
      • colors.windowTitleBar.bottom (Default is “#AAA”)
    • colors.contentBackground. (Default is “#F8F8F8”) Color of the canvas element behind the content div.
    • colors.closeButton (object) Used to create a the background and stroke for the closeButton.
      • colors.closeButton.fill (object) Used to create a gradient background for the closeButton.
        • (Default is “#F5F5F5”)
        • colors.closeButton.fill.bottom (Default is “#F36”)
      • colors.closeButton.stroke (object) Used to create a gradient stroke for the closeButton (does not work in Internet Explorer).
        • (Default is “#FFF”)
        • colors.closeButton.stroke.bottom (Default is “#F00”)


A system like this is bound to have drawbacks, and the biggest one is probably accessibility. Users with a screen reader or similar device may find the custom modal completely unusable. This is the same problem most RIAs face due to dynamically generated content. I’m considering implementing a check that uses a traditional JavaScript alert, prompt or confirm window in lieu of the custom modal if the user is using a screen reader. The check may or may not be based on whether WAI-ARIA mode is activated, but I have a long way to go before I’m ready for that! (Side note: To see WAI-ARIA in action, check out Google Reader.)

Another drawback is the mingling of my CSS with my JavaScript; in most cases I don’t like using JavaScript to set styles, except to set a classname. However, in this case I want the modal window to be as simple as possible and look nice out-of-the-box without requiring adding CSS files and all that jazz.

Lastly, I’d like to point out that the window doesn’t auto-size to fit the content. However, if the the HTML content doesn’t fit, the main content div will sprout scrollbars, ensuring you still have access to all of the content.

Anyway, this has been a fun experiment for me. It’s taught me a lot about what goes into creating feature-rich and flexible JavaScript widgets. I have nothing but respect for people who make JavaScript-based UI components like the folks behind MochaUI, Dojo, and YUI. It’s a TON of work.

Hawaiian diacriticals

For those of you who haven’t had the pleasure of encountering the Hawaiian language, it’s a very simple but elegant language.  The written form is largely phonetic (cooked up by American missionaries in the 1800s) and makes use of two diacritical marks: the ‘okina, and the macron (also known as the kahako).

An ‘okina usually indicates a glottal stop, which is very important in the pronunciation of Hawaiian words.  The name Hawai‘i is a great example: the ‘okina indicates the name is pronounced hahwhy-ee instead of hahwhy. When you hear a native pronounce the name, there’s usually a very short hard pause between the why and ee syllables.

Unfortunately, the two Hawaiian diacriticals are not used by European languages, which means they’re difficult to accurately represent on a standard US qwerty keyboard. In most printed publications, the authors simply omit the diacriticals altogether — the very reason you usually see the name Hawaii, and not Hawai‘i.

Over the last decade, there has been an attempt by many well-meaning locals (Hawaiian and non-Hawaiian) to use substitute characters when true diacriticals aren’t available. While macrons are usually omitted (they don’t exist in most font sets), the ‘okina is often represented by a foot mark (‘), sometimes (mistakenly) referred to as a straight or neutral single quote mark.

An 'okina. Credit: Wikipedia ( This brings me to one of my pet peeves and the purpose of this post:  misuse of the backtick (`) character. Many of the previously-mentioned well-intentioned folks mistakenly use a backtick to represent an ‘okina, and it drives me absolutely bonkers.

As I mentioned to a friend of mine recently, a proper ‘okina is usually the same as left single quotation mark (‘), depending on the font. The shape of the ‘okina should loosely resemble the number 6. In HTML you can get this character by typing the entity &lsquo;.

Granted, using entities is a pain for most people, and practically impossible in email and other electronic documents.  Substitutions will continue to be made.  I believe a foot mark (‘) is a more accurate depiction of an ‘okina than the backtick (`). It’s also easier to type and looks nicer.

Fun with canvas and MooTools: a Rectangle class

Greg Houston’s uber-cool MochaUI has led me to experiment with the canvas element the last few days.

I first saw MochaUI sometime in 2007. While I was duly impressed, I couldn’t quite find a use for it and filed it away in my bottomless “play with this later” drawer.

Recently at work I realized I needed a good modal window that was more extensible than JavaScript’s built-in confirm and prompt windows. MochaUI looked like a handy way to get slick modal windows into my project, but I soon realized that MochaUI is designed to do much, much more than I need, and therefore is (for my purposes) bloated. So, in typical DIY fashion here at pipwerks, I decided to borrow a page from Greg’s book and make my own MochaUI-inspired modal window using the canvas element, CSS, HTML, and MooTools.

Before I could get into the full modal window code, I needed to understand the canvas element, and learn how to manipulate it. Luckily for me, it isn’t much different than ActionScript’s drawing API. After evaluating what I’d need for my little modal window, I whipped up a MooTools-based JavaScript class that produces canvas rectangles in the blink of an eye. Check out the test suite.

Here’s how you’d instantiate a plain-jane rectangle with no stroke and a pink fill:

var canvas = new Element("canvas", {width:300, height:200}).inject(document.body);
var rect = new Rectangle({
    canvas: canvas
    width: 300,
    height: 200,
    x: 0,
    fill: "#F36"

Want rounded corners? Just add a radius parameter:

var rect = new Rectangle({
    canvas: canvas
    width: 300,
    height: 200,
    x: 0,
    fill: "#F36",
    radius: 9

As demonstrated by the test suite, the class includes the ability to specify the radius of each corner, the fill type and color (solid or linear gradient), and the stroke weight and color (including linear gradient).

For those of you unfamiliar with the canvas element, there are a host of additional options I chose not to build into my class, including join type for lines, radial gradients, and image backgrounds. For the purposes of my modal window, I didn’t need that stuff and wanted to keep it simple (and smaller file size). Feel free to modify the class for yourself, though.

Sometime in the next day or two, I’ll write about my modal window and provide test links. I’ll also cover the fugly hack required to get Internet Explorer to work with canvas.

Until then…

UPDATE: Read about the Modal class here.

PS: Disclaimers:

  1. If you’re wondering why I didn’t include a sample of the class in action on this page, my WordPress install uses jQuery, which conflicts with MooTools. I didn’t feel like fighting it tonight.
  2. I don’t write JS classes often, so I’m sure mine could use some cleanup. Feel free to make suggestions!

Obfuscating email addresses, revisited

A while back, I posted my method for defeating spambots that harvest email addresses. This post is an update to that original method. It explores cleaner, less obtrusive code approaches and more accessible/usable HTML markup.

If you’re impatient and want to jump to some working examples, here you go:

The other “solutions”

So how do you prevent spambots from harvesting your email address? Well, there are a gazillion suggestions out on the interwebs, and unfortunately most of them stink because they require JavaScript, and because they often use illegible or invalid markup. For instance, this example — which was created by an email address obfuscator ranked high in Google searches — uses character entities to render the text completely illegible:

<a href="&#x6d;&#97;&#000105;&#108;&#116;&#000111;&#58;&#000116;&#x68;&#x69;&#000115;&#64;&#x73;&#x74;&#000105;&#x6e;&#x6b;&#x73;&#x2e;&#00099;&#x6f;&#109;"

This method has been popular for a number of years, but has some serious flaws. First of all, how do you know if you even have the right address in there? Secondly, what’s to stop a spambot from reading character entities? I imagine it would be as easy as reading ASCII or UTF. GONG!

Here’s another popular approach, premised on the notion that spambots look for any links using a mailto: protocol:

<script type="text/javascript">
   function emailme(user, domain, suffix){
      var str = 'mai' + 'lto:' + user + '@' + domain + '.' + suffix;
<a href="javascript:emailme('this','stinks','com')"></a>

There are multiple problems with this approach. The first problem is that it doesn’t use mailto: in the markup. This means if JavaScript is disabled, the link is completely useless. It also breaks the sematics of the links.

The second problem is that the JavaScript is inline and therefore obtrusive. JavaScript should not be mingling with your markup… it’s bad form! Any link that starts with javascript: is troublesome in my book.

Lastly, the whole address is still contained in the text of the page. If a spambot is sophisticated enough to look for mailto: protocols, it’s probably sophisticated enough to use RegEx to search for text that uses both @ and a period (.) without spaces.

There are other solutions out there, too, but they all require invalid markup, semantically incorrect markup, or flat-out removal of the email hyperlink. I want a solution that remains clickable when JavaScript is disabled, and doesn’t get all screwy with the markup. These don’t fit the bill. There’s another way.

A cleaner solution

My solution is simple: use an invalid email address. No, really! An invalid address with some extra touches and some unobtrusive JavaScript will work wonders. Here’s how to use it, step-by step:

Step one: Create your markup using a slightly altered address

Begin with a real address, then modify it to include some dummy text. For instance, the address would be rewritten The spambot will harvest the address, which won’t work when the spammers try to use it.

The markup should look like this:

<a href=""></a>

There’s an obvious flaw here: The email address is still written in plain text between the ‘a’ tags. We’ll need to use alternate text — if you want to avoid spambots, NEVER use the real address as the visible text in an email hyperlink.

Using something such as sales AT visitwaikiki DOT com is also probably a bad idea, simply because zealous spambot authors can look for that very common pattern and manage to parse the email address. You’re best off using a different phrase, such as:

<a href="">Contact Jane.</a>
<a href="">Email our sales department.</a>

We still have another problem to address: The link works, but it’s using the wrong address! The next step will help with that.

Step two: Improve the markup to make the link more usable when JavaScript is disabled

It’s always a good idea to ensure your visitor can use the email hyperlink when JavaScript is disabled. As it stands, when the visitor clicks the link, their operating system will create an email addressed to the invalid address Without JavaScript, we can’t correct the address, but we can let the user know that the address needs to be edited.

<a href=" ADDRESS NEEDS EDITING&body=Please remove the text 'notspam' from the address before sending your email.">
   Email our sales department.

The mailto: protocol allows users to tack on additional information using the subject and body options. Whatever is listed after subject will appear in the email’s subject line. Whatever is listed after body will appear in the message’s body. By creatively using these options in the email address, we can clearly instruct the visitor to edit the address as-needed. The code above this paragraph produces the following email when clicked:

Message: Please remove the text ‘notspam’ from the address before sending your email.

Is it a pain to have to include the subject and/or body options each time you write an address? Yes. But is it more of a pain than the hundreds of spam emails you might get each week? I doubt it.

We now have a fully-functioning standards-friendly markup-only spam-resistant link. (Yes, I love hyphens. Don’t you?) Next, we’ll improve the experience for the 95% or so of your visitors who have JavaScript enabled.

Step three: Use JavaScript to make the link behave normally for most visitors

Most of your visitors will have JavaScript enabled; let’s take advantage of this and improve their experience. Our primary goal with our script will be to correct the invalid address by removing the dummy text “notspam”. However, since we’re removing the dummy text, we’ll also need to remove the instructions contained in the subject and body options so we don’t confuse the visitor.

Here’s a simple function that scans the page for all email links, then removes the dummy text (assuming all links use the same dummy text), the subject option, and the body option:

onload approach

window.onload = function (){
   var links = document.getElementsByTagName("a");
   for (var i=0; i < links.length; i++){
      if(links[i].href.indexOf("mailto:") !== -1){
         this.href = this.href.split("?")[0].replace("notspam", "");

Live demo

This teeny bit of JavaScript executes when the page loads and makes all email links behave as expected. Now we have a fully-functioning standards-friendly spam-resistant email link that also degrades nicely for visitors without JavaScript, and looks/feels completely normal to everyone else.

However, if you’re paranoid like me, you’ll wonder: What if the spambot supports JavaScript and looks for email addresses after the page has loaded? Your email address would be just as vulnerable as it was before.

A quick tweak to the script can help: instead of cleaning the addresses when the page loads, we can choose to only clean an address when the link is clicked.

onclick approach

window.onload = function (){
   var addressCleaner = function (){
      this.href = this.href.split("?")[0].replace("notspam", "");
      this.onclick = function (){};
      this.oncontextmenu = function (){};
   var links = document.getElementsByTagName("a");
   for (var i=0; i < links.length; i++){
      if(links[i].href.indexOf("mailto:") !== -1){
         links[i].onclick = addressCleaner;
         links[i].oncontextmenu = addressCleaner;

Live demo

Note: all modern browsers treat a link as ‘clicked’ if you tab to it and hit enter on your keyboard, which means the link remains accessible to those using keyboard navigation and/or screen readers.

Also, notice the oncontextmenu code; when a link is right-clicked, the onclick event isn’t triggered. If a person right-clicks the email address to copy it, they would be copying the invalid version of the address. Using the oncontextmenu event fixes this problem.

You’re done!

You now have a spam-resistant email hyperlink that works whether JavaScript is enabled or not. It adheres to standards (no invalid markup), is semantically correct, and is unobtrusive.

Having said that, you should be aware that this system is not perfect; spammers are very clever, and will always catch up to us. This method is a form of spam resistance, not a foolproof way to defeat all spambots from now until eternity.

While the code you’ve just seen will work fine for most people, there are a few improvements that can be made with the use of a JavaScript framework. If you don’t use a JavaScript framework such as MooTools or jQuery, your journey has ended. If you do use a framework, let’s explore some potential improvements to the system.

Improvements via frameworks

JavaScript frameworks add some impressive tools to our toolbox and provide many conveniences. For this example, I’m going to use MooTools 1.2, but most other frameworks will have similar code that you can adapt for your own needs. Here are some improvements we can make:

  1. Use event handlers instead of direct assignment.
  2. Use a domready event instead of window.onload.
  3. Use CSS selectors and the array:each method

Here’s the improved code, modified to use MooTools 1.2:

window.addEvent("domready", function(){
   var addressCleaner = function (){
      this.href = this.href.split("?")[0].replace("notspam", "");
         "click": addressCleaner,
         "contextmenu": addressCleaner
   $$("a[href^=mailto:]").each(function (a){
         "click": addressCleaner,
         "contextmenu": addressCleaner

Live demo

Explanation of the MooTools framework version

Since some of you may not be familiar with frameworks, so I’ll try and explain the changes I’ve made.

Event handlers

Most JavaScript gurus will tell you that using event handlers is a much more robust approach than using a direct onclick assignment. For starters, adding an onclick event using direct assignment will overwrite any existing onclick event. Using an event handler will ensure the new event will not destroy any existing events, and will simply add the new event to a queue of events.

//Direct assignment
a.onclick = function (){
  //Do something

//MooTools event
a.addEvent("click", function (){
   //Do something

As you can imagine, if you don’t use a framework, browser support and cross-browser incompatibility issues make event handlers a bit of a pain. This is one of the primary reasons frameworks have become so popular: they take the pain out of cross-browser compatibility.

Change window.onload to a domready event

The domready event is executed earlier than an onload event. domready basically means that all markup has loaded into the browser DOM, even if images and other media haven’t finished downloading yet. onload, by comparison, only fires after everything has finished loading. A MooTools domready event looks like this:

window.addEvent("domready", function (){
   //do something

Use CSS selectors and the array:each method

MooTools allows us to replace document.getElementsByTagName with much more targeted CSS-based selector: $$("a[href^=mailto:]"). This selector finds all links on the page whose href attribute begins with mailto:, then places the results in an new array. This means we can ditch two elements of our original script: the call to


and the if syntax inside the loop:

if(links[i].href.indexOf("mailto:") !== -1)

Next, we can replace the for loop with an each method, which performs whatever action is specified to each of the items in the array.

myArray.each(function (arrayitem){
   //do something with arrayitem

The each array method is native to browsers not named Internet Explorer. Frameworks like MooTools and jQuery bring support for this function to browsers that don’t natively support it.

Now that we’ve got our CSS-based selector working with the each method, we can greatly simplify our code:

window.addEvent("domready", function(){
   var addressCleaner = function (){
      this.href = this.href.split("?")[0].replace("notspam", "");
         "click": addressCleaner,
         "contextmenu": addressCleaner
   $$("a[href^=mailto:]").each(function (a){
         "click": addressCleaner,
         "contextmenu": addressCleaner


  • You can place the dummy text in any part of your email address, not just the username portion. For instance, you could do, sales@visitwaikiki.commie, etc.
  • It’s probably a good idea to use dummy text other than the common phrase “nospam”; authors of spambot software can easily look for these phrases as keywords and use them to target your address. Get creative with your dummy text, just be sure it’s obvious to a human reader that the text needs to be removed.
  • If you have multiple email addresses on the page, this method requires that you use the same dummy text in all email addresses.
  • Be sure you change the dummy text in the JavaScript function to match whatever text you decide to use!

Known Issues

When JavaScript is disabled and someone copies/pastes the email address instead of clicking it, they will be copying the invalid version of the address. To minimize problems, you can write the address in a hard-to-miss way, such as using all caps for the dummy text ( This will be an extremely small percentage of users, so I wouldn’t worry too much; if they’re savvy enough to disable JavaScript and use copy/paste for email addresses, they’ll probably read the address, too.

This email address obfuscation method has been successfully tested in the following browser/OS combinations:

  • Firefox 3.0 (Mac OS X, Windows Vista)
  • Safari 3.2.1 (Mac OS X, Windows Vista)
  • Internet Explorer 6 (Windows XP)
  • Internet Explorer 7 (Windows Vista)
  • Internet Explorer 8b1 (Windows 7 beta)
  • Opera 9.6 (Mac OS X, Windows Vista)
    • One issue in Opera: The contextmenu menu event doesn’t trigger correctly when right-clicking