Do not use the alert function in javascript 2007-05-16

Picture yourself on a beautiful beach on a warm day. The sounds of the waves is music to your hears. You're on a comfortable chair with a laptop on your knees connected via an incredible WiFi. You're using a brand new web2.0 application that must be the gratest web site on the web. Then, you see an infamous alert from javascript…

Back to reality

This alert box from javascript brought you back to reality. You're in your shitty room, alone. The smell is disgusting. Everything is dirty. All because a developer has used the alert function to tell you something in an application. Don't let this happen on your web application. Never, ever, ever use an alert box.

History of the alert

The alert was invented in the web1.0 era when it was the only way of showing a dynamic message to a user. That was the time when people loved win32 applications because they were so easy to use (compared to a web application). To have a little bit of win32 in their web world, they (some bad people) created a monster : the alert function that shows a win32 window.

It was it a big mistake because lazy developers still use it because it is so easy. Don't fall in the trap. Do not use the alert function.

The problem with alert

The user have to click on the message before he can do anything else on the page. Users hate to click. Don't make them click and show an unobtrusive message that the user doesn't have to click to continue.

What should I use instead of alert?

Anything else. This includes (but is not limited to)

Light boxes I personnally don't like light boxes but they have the momentum at this moment. There are hundreds of library that can help you with them so don't implement another one and re-use an existing one please… Contextual messages Why not show a message where it happened. A little knowledge of DHTML and you're ready.

Example. On Ecstatik! (a project on which I worked), when there's an error with the ajax vote, the label “I laughed!” is changed to “error!” written in red. Maybe it's not the idea of the century but it works and it tells you where the error is. Fading in/out messages These ones are more difficult to do but Google and Wordpress do it elegantly. Use a library with a fading in/out function and show a message at the top of the page (or anywhere visible by the user). The user will get used to see messages at this place and will like the fact that they don't have to click.

Note I expect a lot of people to tell me that I use them in almost all my examples. These are examples and I don't want to begin to write DHTML just to show the result of bunch of javascript lines.


How to use the self with object-oriented javascript and closures 2007-05-14

When I began with object-oriented javascript, I always saw a self here and there without fully understanding what it meant.

Self?

When you see self in some object-oriented javascript, it's just mean that the developer is using a closure that will reference the current object via a variable named self. Because self is a variable, it could be named anything else. The use of “self” as a name is a unwritten convention but it could be whatever you want.
// Create a cat
function Cat() {
    this.theCatName = "Mistigri";
}

// The cat will meow later Cat.prototype.meowLater = function() { // I create the variable self that refers to the this (the current object) var self = this;

// I create a timeout that calls the self.meow function within an anonymous function
/*** NOTE : You don't always have to create an anonymous function it's just that in
    this case, it is required ***/
window.setTimeout(
    function() {
        self.meow();
    }
    , 1000);

}

// The cat meows
Cat.prototype.meow = function() {
    // I can use the this expression!!!
    alert(this.theCatName + " : meow!");
}

// I crate an object and call the meowLater() function var theCat = new Cat(); theCat.meowLater();

Why not use the this?

Because when using closures within an object, the this in the called function (in the above example, in the meow() function) is the window object.


Our last project : Ecstatik! 2007-05-10

Frank (of Ruby Fleebie) and I have been busy lately. We worked together on a project called Ecstatik!

What is Ecstatik!?

Ecstatik! is a project that caused Frank and I to be busy lately. But it's not just that.

Ecstatik! is a digg-like for funny stuff. No more than that. We didn't want to make the world a better place, we wanted to have a common project and get it done. A project that would break the classic cycle of “I have a project and it will be big” and ends up in a black-hole somewhere in the universe.

For the moment, there's no fancy features. Not even a good looking design. These things will come one day but the main idea is keep it simple, stupid. This is an overheard expression but an underused one. I think that this time, we've done it.

How is it done?

Ecstatik! is all Rails. It was my first time and I rediscovered how pleasant could be the server-side development. I worked with PHP a lot recently and was bored of it. It is so redundant. Create an object. Write a form to create/edit the object. Write SQL to handle this object. Write some more SQL to work with objects that are linked. I hate that! Rails does all that redundant work for you and if you want, you can modify or optimize it without being restricted. This is the way life for a developer should be.

Don't hesitate and go for Rails!

The javascript side

I didn't write a lot of javascript because I wanted learn as much as possible about rails. For the voting process, I used ajax/json via JQuery. This javascript library is simply amazing.
  • The selectors combine javascript, css and xpath. It is the most complete HTML object selection ever seen by human.
  • The manipulation of HTML object are easily modifiable.
  • The ajax support offers all we could want of ajax.
Take a look at ecstatik! and have fun!


How to use JSON 2007-05-08

UPDATE : This was written more than 2 years ago, read the new post on How to use JSON.

Web2.0 came with the intensive use of the XMLHttpRequest object even if it was already in our browser before then. A lot of format were tried but JSON will be the winner overall.

What is JSON?

JSON is a format for communication between the server-side (PHP, ASP.NET, …) and the client-side (javascript). The magic of it is that the response from the server-side can be easily converted to an object via the use of the eval() function.

Eval() is a function that gives you the possibility to execute some code in javascript from a string.

eval("alert('This is from eval()')");
This is a bad idea to use it in your code but so easy for JSON that you have to use it.

How to JSON on the server-side?

You can work like an idiot and create your own JSON marshaller for your project or you can go to json.org and use one of the objects that you can find.

I'll take PHP as example. You want to send an object to javascript. You simply do

$response = array();
$response["id"] = 3;
$response["message"] = "The object was saved";
echo(json_encode($response);

It will echo

{id : 3, message : "The object was saved"}

How to JSON on the client-side?

Use the eval() function.

var json = eval(theServerSideJsonTextResponse);
You can now use the json variable created like this
alert(json.id + " : " + json.message);
and it will alert
3 : The object was saved
Beware! There may be an invalid label error here. The solution is to add parenthesis to the response.
var json = eval("(" + eval(theServerSideJsonTextResponse); + ")")
#UPDATE : May 10, 2007 As it was pointed out in the comments, you should never use eval directly when parsing JSON on the client-side. Use a existing JSON parser or a library (jquery is my favorite).

Other formats

For sure there are hundreds of ways of sending back a response to javascript but to my experience, JSON is the best. Let's take a look at the others.

XML is for purists with a lot of time to spend Do you really want to write a XSD (or DTD) for all the calls that can be made to the server? Anyway, it's long to develop because you have to parse it all.

HTML is for lazy people Though it's not completly wrong, laziness is often a bad thing. What do you do if you want to reuse information that you got in a HTML? You parse the HTML to extract the info? please don't…

CSV is for the people that are stuck in the 90s CSV was the coolest thing back in the 90s along with Fresh Prince of Bel-Air.

Watch out for BISON

BISON is nothing else than Binary JSON (see this article). It's lighter than JSON but still unstable. My guess is that we'll all use it sooner or later… but it's just a guess…


How to do a non-destructive overwrite of a function in javascript 2007-05-03

I really don't like the “non-destructive” expression but I couldn't come up with a better one.

What?

You want to create a function but you will overwrite the old one. You just want to add some code before or after it.

Example, you create a javascript applet that can be added to web sites you do not own and you want to call a function in the body.onclick() event. Maybe the site already has something in the body.onclick() event and you don't want to overwrite it because the other developer will be mad at you. You're stuck!

How?

First of all, don't panic. Take a deep breath and relax.

Now, you're ready.

var oldBodyOnClick = body.onclick;
body.onclick = function() {
    // Add your code here!
    alert("Before the old event");

if (oldBodyOnClick != null) {
    oldBodyOnClick();
}

// or here!
alert("After the old event");

}

Could you repeat slower please?

Ok.

First, I assign the body.onclick() event to a new variable.

var oldBodyOnClick = body.onclick;
Second, I create a new function that will be called on the body.onclick() event.
body.onclick = function() {
Third, I add code before the old event
alert("Before the old event");
Fourth, I call the old event if it is not null
if (oldBodyOnClick != null) {
oldBodyOnClick();
}
Third, I add code after the old event
alert("After the old event");
That's it!