Format strings with Mootools

Posted in development by Kris Gray on January 29th, 2009

Remember String.Supplant()?

Its the nifty little tool that lets you do this.

  1. "The date today is {todayDate}, thank you {name}".supplant(
  2.   { "todayDate" : new Date().toString(), "name" : "Clark Kent" }
  3. );

Normally you would need to include the prototype supplied by Douglas Crockford on the page for you to be able to use this, but if you are using the Mootools library then its already built in.

String Method: Substitute

  1. var myString = "{subject} is {property_1} and {property_2}.";
  2. var myObject = {subject: 'Jack Bauer', property_1: 'our lord', property_2: 'savior'};
  3. myString.substitute(myObject); //Jack Bauer is our lord and savior
No comments

Enabling the Back Button in Ajax Applications

Posted in development by Kris Gray on January 26th, 2009

Overview

Enabling the back button isn’t quite as difficult as it might sound, especially for a project that your starting from scratch. Here’s a simple example and then we’ll go through the techniques needed to make this happen.

Change Background Color To

If this is not working for you, then you can try this test page.

As you click the different buttons, you should notice the URL of this page is changing. The key is this portion below.

#change-background:990000

When we change the hash of the page, we aren’t requesting a new page from the server, the browser thinks we are navigating to a new portion of the page. (Some people know that if there was an ID of change-background:990000 on the page, the browser would attempt to focus on that element) Because of this, it creates a history entry that we can use to track back button usage, and deep linking.

Note on browser inconsistencies

Now obviously not all browsers handle this the same way, thus we use a library which abstracts all these problems away from you and lets you only worry about your application. The library we are using here is RSH (Really Simple History). Here are a few other libraries you could use.

Code

Lets look at the code necessary to implement this feature.

  1. <h4>Change Background Color To</h4>
  2. <ul class="button-list">
  3.     <li><a class="post-internal" rel="465e77" href="/denim/index.php">Denim</a></li>
  4.     <li><a class="post-internal" rel="990000" href="/maroon/index.php">Maroon</a></li>
  5.     <li><a class="post-internal" rel="000000" href="/black/index.php">Black</a></li>
  6. </ul>

This is the HTML for the 3 buttons, some of the important things to note here.

  • I tagged each button with a “post-internal” class. This allows me to create a generic function that attaches the history logic.
  • I attached the history information to the element. I typically use the rel to attach information to elements, I don’t know why, its just the way its always been done.
  • I’ve added an href, so if the user doesn’t have Javascript enabled, they could navigate to the separate index pages in the color directories which would know they need to color the page. This is certainly overkill for a background color change, but its one of the important aspects of unobtrusive Javascript.

Obviously the heavy lifting is in the Javascript.

  1. window.dhtmlHistory.create({
  2.         toJSON: JSON.encode,
  3.         fromJSON: JSON.decode
  4. });
  5.  
  6. window.addEvent("load", function() {
  7.     window.dhtmlHistory.initialize();
  8.     window.dhtmlHistory.addListener($listener);
  9.    
  10.     $$(".post-internal").addEvent("click", function(ev) {
  11.    
  12.     window.dhtmlHistory.add("change-background:" + this.getProperty("rel"));
  13.    
  14.     //--- Event Code
  15.     changeBgColor(this.getProperty("rel"));
  16.    
  17.     //--- Don't go to the HREF address.
  18.     new Event(ev).preventDefault();
  19.     });
  20. });
  21.    
  22. function $listener(newLocation, historyData) {
  23.     //--- If not the url event we are looking for, escape.
  24.     if(newLocation.indexOf("change-background:") == -1) return;
  25.    
  26.     //--- Set the background of our HTML element to the color specified in the URL.
  27.     changeBgColor(newLocation.replace("change-background:", ""));
  28. }
  29.  
  30. function changeBgColor(newBgColor) {
  31.     $(document.body).setStyle("background", "#" + newBgColor);
  32. }

This is the entire contents of my sample script file, so we’ll go down through each section.

  1. window.dhtmlHistory.create({
  2.         toJSON: JSON.encode,
  3.         fromJSON: JSON.decode
  4. });

RSH creates itself in the property window.dhtmlHistory, so thats already going to be there for you. RSH uses some JSON to track its history data, so you’ll need to supply it some methods for serializing and de-serializing. It does come with these methods in a separate file, but since Mootools already includes these, I just used the ones from Moo.

This you can go ahead and do outside of any events.

  1. window.addEvent("load", function() {
  2.     window.dhtmlHistory.initialize();
  3.     window.dhtmlHistory.addListener($listener);
  4.    
  5.     $$(".post-internal").addEvent("click", function(ev) {
  6.    
  7.     window.dhtmlHistory.add("change-background:" + this.getProperty("rel"));
  8.    
  9.     //--- Event Code
  10.     changeBgColor(this.getProperty("rel"));
  11.    
  12.     //--- Don't go to the HREF address.
  13.     new Event(ev).preventDefault();
  14.     });
  15. });

A bunch of stuff here, we attach our initialization logic to the window load event as RSH explicitly states

RSH will break, especially in IE, if you try to initialize it from any flavor of DOMContentLoaded.

Once in the loaded event, we call initialize to start the process, and then we add our listener. This listener function is what will get called every time someone hits the back button, forward button, or even the page being loaded with a hash value.

Inside the onload event, we add our onclick event for the buttons.

When the button is clicked, we use the add() method of RSH to add a new history entry. While the listener method is probably 40% of the logic you will need to provide to implement history tracking, this single call is the other 40%. Really those two features make up the meat of it.

The value we pass to the add needs to be descriptive enough that we can figure out what to do with the information in our listener event. In my example, I’m appending “change-background:” to the hash code, so when my listener fires, I know that it has the information I want (someone else isn’t doing some other history tracking) and that I know what to change the background to.

Now when you add a history entry, RSH does NOT fire the history change event listener. (It really should, more later) So you need to also attach your logic for the event as well, which is a simple changeBgColor method with the rel information of the clicked on link.

Lastly, we don’t want to actually go to the URL specified in the anchor tag so we use preventDefault() to cancel that.

  1. function $listener(newLocation, historyData) {
  2.     //--- If not the url event we are looking for, escape.
  3.     if(newLocation.indexOf("change-background:") == -1) return;
  4.    
  5.     //--- Set the background of our HTML element to the color specified in the URL.
  6.     changeBgColor(newLocation.replace("change-background:", ""));
  7. }

This is our event that gets fired every time the history changes. When our listener here gets fired, it looks to see if any change-background information is in the URL, and then it parses out the hex value and calls the changeBgColor method.

With this method, you’ll want to start thinking of the URL as a full description of the state of your application. The less you track in your URL, the less the user can bookmark to, and the less they can back button out of. The extent to which you implement this is totally up to you, and admittedly this could make your URL quite complex…

Gripes about RSH

I wanted to use RSH because its had quite a bit of development on it, so I assumed it would be a solid bug free library. Plus it has one purpose, Ajax applications history tracking, unlike SWFAddress which has some integration with Flash and thus feels like using the wrong tool for the job sometimes.

Though I have a big problem with it not firing the listener event when we use the add() method. Since we put all the information in the URL, and we have to write the listener method to parse that information and set the page to that state, there’s no reason to put that logic anywhere else. Be aware you won’t always have to duplicate your code like this in the other libraries, SWFAddress specifically.

One last note about Deep linking

When you implement the back button, you get deep linking for free. I know, you rarely get things solved for free, but since we are using the URL to describe the state of our application, when the page loads up RSH will fire off our listener event notifying us theres some information in the hash. From there, our application doesn’t care how that information go there, its just going to operate on it.

Download Sample Code

Justise-BackButton.zip

7 comments

Project Retrospective Demeter Group

Posted in development,Retrospective by Kris Gray on January 16th, 2009

Demeter Group Website

This is the first version of the Demeter Group website, it’s a flat HTML site with no CMS and has some usage of JavaScript to allow for in page browsing.

Some notes from this project.

  • Working with people who you recognize is lots of fun. These guys actually worked with Method the soap company; GU2O is a product I’ve used in the past during my runs; and I keep seeing their products at various stores which gives me a sense of pride that in some small (very very small) way I contributed to the success of that product.
  • I experimented with another layout for my JavaScript. I’m trying to find the right type of techniques for each different size of website; in this one I did a new class for each page, and since some of the pages were similar, I utilized a base class for those.
  • On this project, I estimated about a day for the back button implementation as the last time I did it on Method.com it took forever. When it came time to implement it, it took about 2 hours. Now I’ve done it so many times, 30 minutes is enough time.
  • Getting a new designer in the middle of the project sucks. Unfortunately the designer who created the design moved back to Seattle right before I started coding, so a new designer had to pick up where he left off. This wasn’t fun for either of us as its hard for another designer to answer to the original designers intent.
  • In JS Libraries like M and jQuery, you should use lowercase in your CSS selector searches. WebKit based browsers (Safari, Chrome) don’t like the uppercase tag names. I really haven’t investigated it, but I would assume the tag names are in lower-case and the libraries tend to use methods that do css searches that care about such things. (querySelectorAll, querySelector).
javascript

  1. //--- Safari doesn't like this
  2. $$("BODY").addEvent("..", function(){});
  3.  
  4. //--- It prefers this
  5. $$("body").addEvent("..", function(){});
  • Make sure you cancel your animations for mouse-over events if the user navigates to another element with an animation.
  • Content is the hardest part of any project. Its hard to create, hard to plan for without, and rarely fits at the end.
No comments

Biggest problem with reset stylesheets? List style type inheritance.

Posted in development by Kris Gray on January 13th, 2009

Lately I’ve been running into issues using the Yahoo Reset CSS file.  Typically we can account for every situation when developing our templates to be handed off to the client, and so anything the reset stylesheet removes, we can just add back. But it turns out thats not true. 

For our latest project, we did templates for the Sun JavaFX website. One of the more common things they are doing over there is posting JavaFX samples and tutorials on how to program with the new framework. In so doing, they ended up doing quite a bit of lists and sub-lists. We all expected this not to be a problem, but when it came time to input the content we found the reset stylesheet was a little two agressive. 

Here is what you would expect a normal list with some sub-lists inside of it to look like.

expected

Now after we’ve applied the following CSS ripped right from the Yahoo Reset css file, we will have killed all the bullets and numbers.

  1. li{list-style:none;}

Lists and Sub Lists with No Bullets

From here, everything seems kosher, except that we now need to add some bullets and numbers back in. From here it gets hairy. 

For all browsers except the one you love to hate (IE 6 -8) you can do this.

  1. li{  list-style-type: inherit; }

That will bring back the browser based list style inheritance.  Yet for IE, this doesn’t work, you get no bullets/numbers at all. Certainly annoying, but we have to work past this, so lets think about a solution.

  1. ul li { list-style-type: disc; }
  2.  
  3. ol li { list-style-type: decimal; }

Then we have to account for UL’s inside UL’s being different and UL’s inside UL’s inside UL’s… yea…

 

  1. ul li { list-style-type: disc; }
  2.  
  3. ul li ul li { list-style-type: circle; }
  4.  
  5. ul li ul li ul li{ list-style-type: square; }
  6.  
  7. ol li { list-style-type: decimal; }
This will result in the following styles.
fail1
Yea we didn’t account for OL’s inside UL’s. To think about it we didn’t account for UL’s inside OL’s either. The combinations here are pretty extensive.  You’ll basically need a new set for each level deeper you go.
We can’t just do

 

  1. UL UL UL OL LI { list-style-type: decimal; } 

because what if the content developer needs to add another UL list? Sigh. 

So recently I’ve been either deleting this statement from the Reset CSS file, or having a special class applied to the bullet type you want, and then you just apply that to the list. This irks me in many ways, but IE tends to do that to me.

  1. ol.bullet li, ul.bullet li{ list-style-type: bullet; }
2 comments