3 reasons why I use jQuery

These days, you can’t write a web application without using one of the billionth javascript library. Two of them stood out of the crowd : prototype and jQuery. I will explain why did I choose jQuery.

Prototype

Prototype is comfortably installed in a lot of developers mind because of two reasons : it was the first widely used and script.aculo.us. Being the first accepted library is a hard thing to do and it will always help them. Scriptaculous (I hate to write it with the dots) had an incredible effect on the popularity of prototype. For the first time, we could do “flash animation” without using flash. This was instant popularity.

jQuery

jQuery is one of the bastard child of prototype. It reuses the $() function but brings it to a level you never could have hope for. In fact, jQuery is almost completly based on the $ sign. Why? Maybe because it’s fast, maybe because it’s trendy. I don’t know. Example, you want to download a JSON from a server, $.getJSON(“http://www.thesite.com/thejson”).

Reason #1 : The selectors

jQuery supports a lot of selectors. And when I say a lot, I really mean a lot. First, there’s CSS selectors. You just have to apply what you know about CSS and you can write many complex selectors.

Second, there’s XPath selectors. When I was young (sic!), I wrote a lot of XSL. And when I say a lot, I really mean a lot. XSL makes an intensive use of that XPath thingy. Because XHTML is basically XML, we could use XPath to easily navigate throught the DOM. The problem was that before jQuery, nothing could do that. Now, we can!

In comparison, prototype just has the $(‘theId’) to select a element. Ouch!

Reason #2 : The Attributes

It’s easy to add/remove attributes to any HTML element. I use it when I create new elements or when I need to add/remove a css class on an element. The interesting thing is that you can chain them and it will work. Example, I want

  1. $("div").attr("title", "This is a div").addClass("newClass");

You can add as many as you want…

Reason #3 : Ajax and JSON

Once again, ajax is now easy as 1,2,3. I wrote an article on JSON and in my mind, there’s no real alternative to JSON. jQuery helps you with it.

  1. $.getJSON("http://www.thesite.com/thejson",
  2.         function(json){
  3.                 alert("I received the json and put it in the json var : " + json.toString());
  4.         }
  5. );

It’s a little more complex with prototype.

How to know if it’s a leap year

It always happens : you have some calculation to do with a date and you forget to calculate those friggin’ leap years. Here’s how to do it cleanly.

The first way

Almost every one use this simple rule : if it’s divisible by 4, it’s a leap year. So the code is

  1. var isLeap = theYear % 4 == 0

Wait a minute, I forgot something! If it’s not divisible by 100 but by 400 it is not a leap year… or maybe divisble by 100 and not by 400…

I can’t remember that! Let’s do it another way.

The one and only way

  1. var isLeap = new Date(theYear,1,29).getDate() == 29;

Nice! That’s something simple that I enjoy. Let’s dissect it.

  1. new Date(theYear, 1, 29)

This line simply create a date object that is initialized with the variable theYear. 1 is the month. As in java, the months are 0 = january and 11 = december (I hate that!). 29 is the last day of february when it’s a leap year.

  1. .getDate()

Returns the date part of a date (sic!). It means that for May 23, 2007, it will return 23.

  1. == 29

That’s the magic part of it. As I said in Mastering the date object in Javascript, there’s a special twist that let you work with dates differently than in most of the languages that I used before. When you initialize a date at the 29th day of february on a non-leap year, it will simply use the date March 1, 2007. So a call to the getDate() function would return 1 and not 29.

How to inherit classes in javascript

First of all, since I made the front page of Ajaxian, a lot of new readers joined in. Welcome to all of you. I would also take a moment to explain that Javascript Kata is a technical blog about javascript and though I will talk here and there about ajax, it is not focused on that subject. It is more about the good javascript techniques that should come along with all the ajax you have to do. I update this site 2 or 3 times a week. Keep reading!

There are hundreds of ways to do inheritance in javascript but a single one is simpler, cleanier and prettier than all the other ones.

Note!
Before reading this article, you should take a look at
How to create objects in object-oriented javascript.

A one-liner

To inherit a class in javascript, it’s a one-liner

  1. TheSubClass.prototype = new TheParentClass();

As simple as that!

Where to write the one-liner

The problem with that one-liner is where should it goes? Once again, the answer is simple : after the constructor of the sub-class. It may look strange but it is extremely effective.

  1. /* The constructor of the Mammal class */
  2. function Mammal() {
  3. }
  4.  
  5. /* The constructor of the Cat class */
  6. function Cat() {
  7. }
  8. // The magic that inherits Cat from Mammal is here!!!!!
  9. Cat.prototype = new Mammal();

Is this true inheritance?

In the hundreds of other ways of inheriting classes in javascript, I think that this is the only one that is a true inheritance. What do I mean by true inheritance? I mean that javascript recognizes it as a sub-class of the class. Check this out!

  1. /* Above code goes here */
  2.  
  3. // Create a cat
  4. var theCat = new Cat();
  5.  
  6. // Check if the cat is an instance of the Cat class
  7. if (theCat instanceof Cat) {
  8.     alert("theCat is an instance of the Cat class");
  9. }
  10.  
  11. // Check if the cat is an instance of the Mammal class
  12. if (theCat instanceof Mammal) {
  13.     alert("theCat is an instance of the Mammal class");
  14. }

If you execute this code, you’ll see that the cat is an instance of the Cat class and the Mammal class.

Do not use the alert function in javascript

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

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.

  1. // Create a cat
  2. function Cat() {
  3.     this.theCatName = "Mistigri";
  4. }
  5.  
  6. // The cat will meow later
  7. Cat.prototype.meowLater = function() {
  8.     // I create the variable self that refers to the this (the current object)
  9.     var self = this;
  10.  
  11.     // I create a timeout that calls the self.meow function within an anonymous function
  12.     /*** NOTE : You don’t always have to create an anonymous function it’s just that in
  13.         this case, it is required ***/
  14.     window.setTimeout(
  15.         function() {
  16.             self.meow();
  17.         }
  18.         , 1000);
  19. }
  1. // The cat meows
  2. Cat.prototype.meow = function() {
  3.     // I can use the this expression!!!
  4.     alert(this.theCatName + " : meow!");
  5. }
  6.  
  7. // I crate an object and call the meowLater() function
  8. var theCat = new Cat();
  9. 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!

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

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.

  1. 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

  1. $response = array();
  2. $response["id"] = 3;
  3. $response["message"] = "The object was saved";
  4. 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.

  1. var json = eval(theServerSideJsonTextResponse);

You can now use the json variable created like this

  1. 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.

  1. 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

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.

  1. var oldBodyOnClick = body.onclick;
  2. body.onclick = function() {
  3.         // Add your code here!
  4.         alert("Before the old event");
  5.  
  6.         if (oldBodyOnClick != null) {
  7.                 oldBodyOnClick();
  8.         }
  9.  
  10.         // or here!
  11.         alert("After the old event");
  12. }

Could you repeat slower please?

Ok.

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

  1. var oldBodyOnClick = body.onclick;

Second, I create a new function that will be called on the body.onclick() event.

  1. body.onclick = function() {

Third, I add code before the old event

  1. alert("Before the old event");

Fourth, I call the old event if it is not null

  1. if (oldBodyOnClick != null) {
  2. oldBodyOnClick();
  3. }

Third, I add code after the old event

  1. alert("After the old event");

That’s it!

How to execute javascript code directly in your browser

This trick is not known by everyone though it is really simple.

The address bar

In the address bar, you simply write

  1. javascript:/*some javascript code here*/;void(0);

As easy as that.

In fact, it’s the same thing as creating a link that executes some javascript code.

  1. <a href="javascript:alert(‘Some code from a link’);">Execute code from javascript</a>

The only thing I add is the void(0); at the end of the code to avoid a “bug” that reloads the page.

Hey, if you want to write a bookmarklet, you’ll probably use this technique.

Firebug

These days, you can’t write javascript without using Firebug (apart if you are a javascript magician). You just can’t. For the ones who don’t know Firebug, I’ll describe it in 7 words : javascript debugger, html inspector, css modifier, fun.

On the “Console” tag, there’s one line beginning with “>>>” at the bottom. This is the javascript executer. If you click the red arrow at the end of the line, you have a multi-line executer.

I always use it to write and test the javascript snippets on this site.

What can I do with that?

Everything you want. In fact, I use it for these purpose :

  • write code snippet for Javascript Kata
  • write a bookmarklet
  • debug javascript on Firefox
  • have fun on other’s sites

Mastering the date object in javascript

Javascript has a pretty basic Date object. It is cool but not as cool as in other languages. In fact, it is different but we like it anyway.

The primitive value

A date is nothing else than the number of millisecond since January 1, 1970 00:00:00. So now is 1 177 603 737 358.

When you create a Date object, it is initialized at now. To alert the primitive value (the number of milliseconds since 1970), I simply do.

  1. var now = new Date();
  2. alert(now.valueOf());

Adding and subtracting

Note : You have to know that months in javascript are 0 = january and 11 = december. Just like Java.

This one is easy. When I want to add a number of days (or anything else) to a date, I use the getDate() and setDate() function. When you don’t know that the setDate() function (and setHours, setMinutes, setMonths…) has some magic in it, you may have a hard time manipulating the dates.

So, I want to add 3 days to the current date.

  1. var now = new Date();// Add 3 days
  2. now.setDate(now.getDate() + 3);
  3. alert(now);

The problem is when you want to add 3 days to December 31 2006, it should return January 3 2007. No problemo!

  1. var now = new Date();
  2.  
  3. // Set to December 31 2006
  4. now.setYear(2006);
  5. now.setMonth(11);
  6. now.setDate(31);
  7.  
  8. // Add 3 days
  9. now.setDate(now.getDate() + 3);
  10.  
  11. alert(now);

You see that the date is correctly computed. You can do the same things with all the other parts of the date. Magic is in the air!

No formatting

There’s no way of formatting a date to a string except if you use concatenation.

If you want to display the YYYY-MM-DD format, you’ll have to do this ugly code.

  1. var now = new Date();var nowStr = now.getFullYear().toString() + "-" +
  2.     (now.getMonth()+1 < 10 ? "0" + (now.getMonth()+1).toString() : (now.getMonth()+1).toString()) + "-" +
  3.     (now.getDate() < 10 ? "0" + now.getDate().toString() : now.getDate().toString());
  4.  
  5. alert(nowStr);

Maybe you won’t do it as ugly as this but it won’t look pretty. Maybe you should check for a librairy.

The Date.parse() function

Don’t use the Date.parse() function. I don’t even know which format it takes. It looks like month[sep]day[sep]year but I’m not sure. Better use some regexp and use the set[DateUnit]() function accordingly.

getYear() VS getFullYear()

You should not use the getYear() function. For an obscure reason, it returns the number of years since 1900. You don’t want to use it. Trust me.

You are now a master

That’s what you need to know about javascript Date object, you are now mastering it.

Do you have something else to add?