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.

JavaScript:
  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

JavaScript:
  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.

HTML:
  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.

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.

JavaScript:
  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.

JavaScript:
  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.

JavaScript:
  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 Retrospective, development 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.

CSS:
  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.

CSS:
  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.

CSS:
  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...

 

CSS:
  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

 

CSS:
  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.

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

No comments

The Ajax Experience: The Rest

Posted in the ajax experience by Kris Gray on October 15th, 2008

Day 2 was easily the most information packed and exciting of the 3 days.

IE8 was a Sponsor this year, yet their involvement was still quite small in the conference. They did have several speakers, but you can tell the conference is still being driven by the Sitepen (Dojo), Google (GWT, Chrome) and Mozilla (jQuery, etc) groups.

Faster then Light JavaScript

The opening talk was from Brendan Eich. Brendan is in a strange situation where is his the master and overlord of JavaScript, yet you can tell he's a bit more intellectual then the typical JavaScript guru. He focuses a lot about lower language constructs and less about closures and the like, which is just kind of weird.

 

  • Tracemonkey
    • Incrementally Rewritten to be much faster
    • Now fast as almost anything.
  • V8, SpiderMonkey
    • Both are very fast and really good codebases.
    • Getting Close to C Speed
  • IE
    • Seaworthy (Showed picture of a beaten down houseboat)
    • Kind of missing in the JavaScript performance arena. 
  • Whats it all mean?
    • Browsers get near native JS Performance
    • Mobile browsers too, without sucking massive amounts of power
    • IE being guilted/pressured into getting better
    • Developers make your voices heard!
  • Canvas
    • Actual image processing capable
    • Ray Tracking Possible now, will be 3-4 times faster in 1 year
    • HTML5 Web Worker threads
  • On the Horizon
    • CSS Transformations
    • CSS3 Selectors
    • Border image
  • Trying to put SVG Back into the web (Though John Resig already voiced his doubts that without a hail mary miracle that SVG is pretty much a goner)
Analyzing Ajax Perf with IE8
I was very suprised that this was a Microsoft IE8 talk. It focused mainly on the new IE8 tools and how to use them to profile Ajax Applications.
  • Javascript Profiler in IE8! (Bet ya didn't know that was coming)
    • Has an IE7 and IE8 Mode
    • Has an API with documentation on MSDN.
  • Native JSON Support
    • Global JSON object with methods to serialize and deserialize objects to and from JSON.
    • Great gains in performance with this object, 10x gain in Serialization, 3x gain in Parsing.
  • IE also has a good Script debugger with the profiler, which of course is 8 years late.
  • Check out more at the IEBlog
The Lightning Rounds
They had this new session setup this year where they have 10 different speakers with 5 minutes each. This was wonderfull, I wish they could do this for all of the sessions of the day so you can get a quick peek on whats going on.
  • Smushit.com - This tool will use different algorithims to shrink all the images on your site and tell you how much you could be saving with its version of your images instead. Awesome tool.
  • Dreamweaver - CS4 presentation, now has some serious JS abilities including native intellisense as well as third party library intellisense. 
  • Hacking Netflix - Bill Scott announced a new API for Netflix. He also showed off the Netflix blog which I've always been curious if they had one.
  • Interviewing JS Guru's - He shows them code and asks them whats wrong with it. Really loves when the people see the XSS issue. Says finding developers with the never good enough Attitute is crucial. Also would like people to know about DNS, Page Caching, how CGI Works.
JSON SOA-Based Client/Server Application Development (slides)
A class based on Dojo communicating with the server REST style.
  • Dojo now has SMD's (Simple Method Description - WSDL in JSON kinda) for Popular API's. Allows you to instantiate an object with a supplied SMD and call methods on that remote service all from within Dojo. 
  • Full Rest Capabilities in Dojo for contacting these services
  • Dojo Secure
    • Framework for bringing together different services in a mashup
    • Adsafe
    • Not done yet, lots of work being put into this area of dojo.
  • No Premature Standardization
    • They don't want innovation to be slowed by standards at this point.
This was a really content filled talk with many different areas being focused on, I ended up paying a lot of attention, understanding only half and getting notes on a quarter. 
State of the Browsers (slides available here)
PPK gave a talk about where we are with the browsers that was 70% relaxing, 30% informative. He started off going into the history of the browser wars, and then the maturation of the browsers through the years. 
  • NN4 and IE4 led to the browser wars of 96-99.
    • Divided the world, basicly you choose a browser and that was what you used. Now adays you choose a browser based mostly on the User Experience, but back then you choose it based on the features.
    • Deliberately incompatible. They wanted you to choose their browser because it had feature X and the other browser didn't.
      • PPK said this didn't work, I think he was refering to the fact that it didn't work for us web developers, but it certainly worked for IE. 
  • These incompatibilities really hurt because if a site didn't work, then it was the site owners fault. Even though the browsers made it so hard for site owners to get them to work in all browsers.
  • Ideology
    • MIcrosoft is EVIL!
      • Why? Just because. They built the better browser, they deserved to win.
    • Worst part of the browser wars.
  • IE Did deserve to win
    • IE 5 was a great browser, it had XMLHTTP.
    • Says nobody was using it at the time, though he wasn't aware of the project I was on in 2000. :)
    • IE5 Mac did for CSS what IE5 Win did for Ajax, it really brought it to the forefront and showed it as a viable technology.
  • Browser Peace
    • Microsoft became complacent.
      • Quiet for 6 years!
    • Allowed other browsers to catch up
      • Firefox now 20-25%!
Here we got into some areas of the browsers  that are still really painfull.
  • Adding rules to Stylesheets
    • insertRule() for all but IE
    • add() for IE
  • Event Model
    • I'm sure you know about this already.
  • Ranges
    • Start / End container works in all but IE
    • Not possible in IE
  • Extensions
    • 99% of the extensions out there really suck
    • 1% are brilliant
      • :hover
      • innerHTML
  • Empty text nodes
    • We don't need to iterate over empty text notes. Sucko!
    • Yet IE will sometimes display white space in the browser, so...
  • mouseenter/mouseleave
    • IE only extension
    • Great extension. The fact that all the JS libraries are including an implementation of it should tell the other browser manufacturers that we need this.
    • Not part of the standard, so not implemented.

I'm trying to get this out the door, so here's some notes from the rest of the conference, very much abbreviated.

 

  • YUI Test was showcased. Check out more here.
    • Still looks a little more complicated then it should be.
    • I think John Resig mentioned a testing framework as a Firebug plugin. That sees like the way it should be.
  • Someone was using the tool Programmers Notepad, which seemed cool so I made a note of it.
  • UX Design for Ajax Apps
    • Design is how things work.
    • The Design of Everyday Things (Recommended Book)
    • Instructions don't make things usable. 
    • Must do Research to determine usability.
      • Don't ask customers what they want, find out what they do.
    • Universal Principles of Design (Another Highly Recommended Book)
    • Tool: Kuler - Generates color palletes
    • Don't Pretend
      • Pretending to be the user means your pretending to be stupid, which just isn't possible. Clients aren't stupid in general, just when dealing with whatever you happen to develop/design.
      • Pretend instead to be the application.
  • Performance from Yahoo
    • Amazon did a test and added a 100ms delay to the loading of their site. They experienced a 1% drop in sales as a result.
    • Yahoo did another test, adding 400ms to their load time, they recieved 5-9% drop in full page traffic.
    • Google, same thing, +500ms to their load time, 20% fewer searches.
    • Get YSLOW! It was an overarching theme of the session.
    • Flush the buffer early if you can, gets the browser working while the server does the rest of its work.
    • Use GET for Ajax requests.
      • Only 1 TCP packet is sent with GET
      • Post sends a headers, and posts body seperately and has a lot more content.
    • Post-load components
      • Whats absolutely necessary to render the page?
      • User percieves site is loaded after site looks visiually loaded. 
      • JS can load in after site looks visually complete.
    • Pre-load components (3 Different types)
      • Unconditional: Google preloads its results images on the google search page.
      • Conditional: On search typing, start preload of images.
      • Anticipated: Anticipating new release? Start pushing out those images for the next release early so the users cache isn't completely empty.
    • Avoid Filters (AlphaImageLoader)
      • Blocks Rendering of the page.
      • Increases memory consumption
      • New filter per usage, not per page.
      • Avoid completely if you can.
      • Use PNG8, works just fine, no grey background, but boolean transparency only.
    • PNG8 Does support alphatransparency, and in IE8 the alpha-transparent bits will show as completely transparent. Didn't understand how to get this to work though, they were vague on it.
    • IPhone
      • Total Cache 1024k
      • 25kb limit on a single file no longer exists.
    • Look out for your users (Don't hurt your users speed)
    • Harvest low hanging fruit
    • Balance features with speed
      • They explained this as, balance the perf budget.
    • Verify Assumptions!
    • Make Perf part of your process.
    • Measure and track results
      • Firebug
      • IBM Page Detailer
      • YSLOW
      • Gomez
      • Smushit.com
    • Ask Questions and Challenge answers
And thats the end.
I had so little time this year during the conference to get all this typed up that it just ended up dragging on. Hopefully I can fix that next year.
2 comments

Next Page »