Archive for the 'JavaScript' Category

>>> $$(selector)

Friday, January 30th, 2009

Gotta love the Firebug console, how can anyone not love the Firebug console. It makes testing random pieces of JavaScript a breeze and best of all - you're playing with the live page. Your page or any page for that matter.

Two nice shortcuts you can use in the console are $ and $$.

The first is like document.getElementById() and the second allows you to get elements by using a selector, like w3c's document.querySelectorAll(), now available in the latest browser versions, including IE8.

So go ahead, give $$ a try. For example you can visit yahoo.com, open up the console and try:
>>> $$('.first')
or
>>> $$('.patabs .first')
or
>>> $$('#tabs1 li')

Lots of fun!

So here's a little example application I came up with, it spits out unused selectors from your CSS. Just paste it in the multi-line console.

for(var i = 0; i < document.styleSheets.length; i++) {
  for (var j = 0; j < document.styleSheets[i].cssRules.length; j++) {
    s = document.styleSheets[i].cssRules[j].selectorText;
    if ($$(s).length === 0) console.log(s);
  }
}
 

smush.it update

Sunday, October 26th, 2008

What's new in smush.it?

  • The old domain smushit.com now redirects to the new one smush.it, which is what we originally intended but the domain registration took a while and we quickly got smushit.com just in time for the Ajax Experience announcement of the tool
  • There's a bookmarklet version of the Firefox extension so you can now run in IE or any other browser capable of bookmarking
  • There's an FAQ
  • The API, while not really documented, is at least described in the FAQ
  • So is the privacy policy. People said we should have privacy policy, we're not lawyers, so we couldn't write something that sounds important. The policy is basically: 1) we won't use the images you upload in any way other than gathering aggregated optimization statistics (how much we save on average, how many files get smushed daily...). 2) Images will be deleted from the server, once we get around to writing some sort of stats script, so download the optimized zip asap, don't rely on it being there for long. 3) The images you upload are available to anyone who can guess the random URL smush.it creates, so don't upload images you want to keep private
  • Flash 10 support, updated to YUI 2.6's flash uploader and sweated a lot to make the uploader work in the tightened flash 10 security, but that's a whole other blog post
  • Smu contest! What's a Smu? We want to know too. Send us you idea of a Smu to smu at smush.it
 

Short Amazon affiliate links - a bookmarklet

Sunday, October 19th, 2008

It's a pain to link to a specific product on Amazon if you have to use their UI to build an affiliate link. It's good to have nice, clean and short affiliate links. This post gives you the details and also a bookmarklet to built the links by visiting the product page you want to link to.

Anatomy of an Amazon affiliate link

Let's see the anatomy of a link in its shortest possible form.
Basically you have:

  • http://www.amazon.com/ - self-explanatory, I think
  • /dp/ - standing for "details product" or maybe "details page"
  • /1847194141/ - a 10 character product code, aka ASIN code, Amazon Standard Identification Number
  • ?tag=affiliatecode-20 - your affiliate code, or tag

For example my Amazon affiliate code is w3clubs-20, and an affiliate link to my book would be:
http://www.amazon.com/dp/1847194141/?tag=w3clubs-20

Amazon also uses longer search engine friendly URLs containing the book title, like:
http://www.amazon.com/Object-Oriented-JavaScript-Stoyan-Stefanov/dp/1847194141/?tag=w3clubs-20

But the book title/product name doesn't really matter, so this is fine too:

http://www.amazon.com/War-and-Piece-by-Stoyan-Stefanov/dp/1847194141/?tag=w3clubs-20

So I went ahead and created a bookmarklet that lets you visit the product page you want to link to, click the bookmarklet and copy a short affiliate URL.

Install the bookmarklet

Drag the link below to your favorites/bookmarks or right-click and add to favorites. Then right click the new bookmark and change its properties, replacing my Amazon affiliate code "w3clubs-20" with yours.

Amazon aff

After installing the bookmarklet, just go to any Amazon product page, click the bookmarklet and it will create an affiliate link for you to copy.

The bookmarklet code, readable version

Here's the code for the bookmarklet, simply find the ASIN (product code) and build a new URL with it.

(function(){
    var aff = 'w3clubs-20';
    if (!document.getElementById('ASIN')) {
        alert('Can\'t find the product ID');
        return;
    }
    var asin = document.getElementById('ASIN').value;
    prompt(
        'Here is the link:',
        'http://www.amazon.com/dp/' + asin + '/?tag=' + aff);
})()

Misc

There's a page in the Amazon affiliates section that let's you check if the links are OK, it's here

Sometimes you might see (usually for non-book products) URLs that instead of /dp/ have /gp/product/, but if you build /dp/ links it's totally fine, according to their link checker, see previous paragraph.

 

Javascript console in IE

Saturday, October 18th, 2008

I'm a sucker for consoles. The ability to quickly type some code and see it executed right then and there... priceless. That's why I'm a huge fan of Firebug's JavaScript console. But what about IE?

option 1 - Firebug lite

Firebug lite is a lighter version of the proper Firebug which runs in browsers other than Firefox. You "install" the bookmarklet and voila - JavaScript console and other goodies are available on any page.

You visit any page and click the "Firebug lite" bookmarklet...
firebug lite bookmarklet

... then you hack away in the shiny console!
firebug lite bookmaklet in action

option 2 - built-in MS script editor/debugger

If you do any javascript in IE, it's a good idea to have this debugger guy enabled. There's actually at least three different debuggers, but one of them is already installed without you lifting a finger. If you enable it, you can debug any time there's a JavaScript error on the page. It also features a console! You can't get to the console unless there's a JS error, so you may need to cause the error yourself. Here's the step-by-step scenario.

Go to menu Tools / Internet Options... / Advanced tab. Under the "Browsing" category uncheck the box that says "Disable Script Debugging"
set the IE options

Go to any page and cause an error, by typing in the address bar some non-existing property or some non-existing object for example. Like javascript:alert(a.a.a)
Go to anypage and cause an error

Non-surprisingly, you get an error, but now you have the option of debugging the error:
A error and a debug option

You're given a list of debuggers, in case you've installed more debuggers from MS. Select your debugger or just hit Yes:
pick a debugger

Just say OK here...
step into procedure

Click "Break"...
Break

Finally - a console! We're in! The console is the so-called "Immediate" window, which is not displayed by default. To see it go to menu Debug / Windows / Immediate. Then just start fiddling with the page. Type anything and hit enter to see it evaluated. You also list the properties of an object by typing its name, like document.images[0] or just document.
Fiddle with document.images[0]

Once you've had your fun, stop debugging:

Enjoy the results of your hard work, a.k.a. replacing some logo with a shot of your favorite book ;)
your fav book

 

JavaScript’s class-less objects

Thursday, October 16th, 2008

javaranch newsletter

"JavaScript's class-less objects" article up at the JavaRanch's newsletter.

Update: and mentioned on Ajaxian, sweet.

 

OOJS book free chapter 8 on YUIblog

Friday, September 26th, 2008

Chapter 8 of the Object-Oriented JavaScript is available at the YUIblog.com. Enjoy!

Chapter 2 is also available at the publisher's site.

Probably thanks to YUIBlog, the book was #7#6 in the JavaScript category on Amazon today, not bad. It's the highest I've seen it, not that I'm obsessed with checking sales rank. It's the journey, not the destination :)

Other than that.. pretty busy lately. Off to Boston for Ajax Experience next week, where I'll be giving 3 (three!) talks. Will have some good stuff to share after that - ppts and a new tool!

 

location=location

Saturday, July 26th, 2008

location = location
... and 534 other ways to reload the page with JavaScript

How many ways you can think of when you want to reload the current page with JavaScript? I counted 535 before I got bored, maybe someone can pick up from there? The cases are so much that I had to write a script to generate them :)

» have fun, see for yourself

Just occurred to me that I didn't even include the frames property in those 535 ways. Consider the limitless possibilities having in mind for example that:

>>> window.frames === window
true
>>> frames === window.self
true

Could you come up with 500 more ways? A 1000? One condition: no recursion, for example window.self.window is not allowed.

 

The book, the book

Friday, July 25th, 2008

OOJS is almost officially out. I mean it's out officially, but not yet up on amazon, which these days means it's not really out, is it. It will probably take a couple more days, maybe next week.

So far there has been a great interest, even enthusiasm, expressed by people running web dev sites who would like to do a review, I'll list the reviews and give link love back as soon as I see the published reviews. If you're interested in reviewing the book on your web site/blog, doing an interview with me or something to that effect, pitch the idea to me (ssttoo at gmail) with your URL, etc, I'll promptly forward to the great marketing folks at my publisher, Packt.

Thanks!

OOJS

 

My online footprint lately

Wednesday, July 23rd, 2008

This is a sort of a catch-up post for listing what I've been up to lately.

  • YUI Blog just published my first article, I'm so proud. It's about loading JavaScript in non-blocking fashion, because JavaScripts, they, you know, like, block downloads. Luckily, there's an easy fix - DOM includes, which I've previously discussed, discussed and discussed.
  • SitePoint published an update to my older article that introduces AJAX, ok, Ajax, by creating a command-line-like interface with PHP on the server side. The updated article features improved code, jQuery example, YUI example, JSON discussion and example. Check it out, bookmark and recommend to your friends that keep asking you "What's this AJAX (they are new, don't know it's now spelled "Ajax") thing? Do you know of a good article?"
  • YDN (developer.yahoo.com) published a video presentation of me and my lovely teammate Nicole Sullivan where we talk about some new and cool front-end performance techniques. So if you wandered how I look and are eager to hear my fabulous Balkan peninsula accent, give it a shot. The talk is called "After YSlow 'A'" and is targeted at those of you who have reached performance nirvana, but are still hungry for more. We talk about preloading components, post-loading, javascript, images, using flush() in PHP to send first byte early on and other fun stuff.
  • Last, not least, I decided to try and find some time to update my JavaScript patterns site. Unfortunately I got sidetracked (yep, I'm easily distracted by shiny objects) and played with a not-so-javascript pattern. The post I published (includes a pretty lame screencast! and) demonstrates how you can use animated background position to indicate loading progress.

Whew, c'est tout pout ce moment, expect a lot more now that the JavaScript book is out of the way. Ah, yep, if you feel like it, join me on Facebook, I created a JS book page.

 

The JavaScript book is almost there

Wednesday, July 16th, 2008

Whew, after a whole year of writing, preparation, edits, blood, sweat, tears, I finished all the latest edits and reviews for my new book, Beginning Object-Oriented JavaScript. It should be out any day now. I can't be happier!

cover.png

You can pre-order with 10% off from the publisher's site.

 

Load a photo in a canvas, then flip

Saturday, May 3rd, 2008

zlati-nathalie.jpg

Today our family went to the yearly photo session with the girls. We took one shot that can be looked normally, as well as upside down, so I was wondering can you flip an image using a canvas tag. Turns out, yes, you can and it's pretty easy.

» Demo is here.

How to load an image in a canvas tag?

Start unpretentiously with an empty canvas tag:

<canvas id="canvas"></canvas>

Now the javascript. Two variables to store a handle to the canvas element and the 2D context of the canvas:

var can = document.getElementById('canvas');
var ctx = can.getContext('2d');

Now let's load an image into the canvas. Using the new Image() constructor you can create an image object, then set its src property to point to the location of the image file. Then set an onload handler for the image which is an anonymous function to be called when the image is done loading. There you put the image inside the canvas using the drawImage() method of the canvas context.

var img = new Image();
img.onload = function(){
    can.width = img.width;
    can.height = img.height;
    ctx.drawImage(img, 0, 0, img.width, img.height);
}
img.src = 'zlati-nathalie.jpg';

You can also notice how the dimensions of the canvas are adjusted to match the dimensions of the image.

How to flip the image upside down

The canvas context provides a rotate() method. The rotation always happens around the top left corner of the image, so we first translate() the image to the bottom right. This way when the image is rotated, it fits back into the canvas. (There is also a one pixel correction, I have no idea why, just saw that the image wasn't flipping exactly otherwise). Assigning this functionality to the onclick:

can.onclick = function() {
    ctx.translate(img.width-1, img.height-1);
    ctx.rotate(Math.PI);
    ctx.drawImage(img, 0, 0, img.width, img.height);
};

C'est tout! Once again, the demo is here.

 

strftime() in JavaScript

Friday, April 25th, 2008

Philip "Bluesmoon" Tellis has posted a tiny (under 3K minified) JavaScript library to format dates, inspired by PHP's strftime()

Examples:

d.strftime('%Y/%m/%d')
» en: 2008/04/25
» fr: 2008/04/25
» de: 2008/04/25

d.strftime('%A, %d %B')
» en: Friday, 25 April
» fr: Vendredi, 25 Avril
» de: Freitag, 25 April

There's also a demo to fiddle with.

I've previously had fun with kinda like the opposite: translating human-readable times into JS Date objects. Also here and here you have strtotime() look-alikes that take human-readable dates and turn them into Date objects.

 

When client-only validation is good for business

Sunday, April 13th, 2008
You should never never ever rely on client-side validation only. Client-side validation is for enhancing user experience, server-side is the validation. This is a rule, never to be broken. But here's a funny story how skipping the server-side validation actually helped.

This is a real story, but the actual names have been replaced in XXX, just not to make other people look bad :D

There is this site called xxxxxxxxx.com that charges you $XX membership access. Having just moved from Canada, last year I didn't have a US credit card to pay the fee and tried to use my Canadian visa. Problem: the input field for postal code (zip code) accepts 5 characters only, since the zip codes in US a like 90404, 90066 and so on. A Canadian postal code is like H0H-0H0 or H0H0H0, six characters. So seemed like I couldn't pay online. Or could I?

Checking the source code with Firebug gives me this:

client.png

From here it's trivial to change maxlength attribute of the input. Even with IE it's super easy just to type in the address bar something like:
javascript:document.getElementsByName('XXXXXXX')[0].maxLength = 100;

So I did change it, typed my Canadian CC#, Canadian postal code and submitted the form, crossing fingers that the developers who built the site were too pressed by deadlines to do a proper server-side validation. Lo and behold, it worked!

At the end with the help of an innocent client-side tweak I got what I needed (membership), xxxxxxxx.com got more business, and everybody's happy.

There's a lesson in this: sometimes being too strict in data validation for things that don't matter is just in your way.
And another: don't assume all your potential clients are from US.

 

JSPatterns.com up again

Wednesday, March 26th, 2008

After getting 300 megs of wiki content spam, I deleted the old wiki over at http://www.jspatterns.com.

Now restarted the project as a blog with static pages for the javascript patterns and blog posts for anything interesting in the ever so exciting world of JavaScript. So far nothing special there (example), but keep an eye on it, as I plan to fill up the TOC (recovered from the old wiki) with top quality content ;)

I suck at design and wasted two nights to come up with some custom wordpress theme for the new blog. I like the result, but that's just me. I also made the theme available for download, in case someone wants to consider it for a future project.

Talking of spam, yesterday my host deleted 2 gigs!!! of email spam from my hosting account, how crazy is that.

The new JSPatterns.com is running the latest release candidate WordPress 2.5, slick stuff.

 

JoJo: Javascript Junk generator

Tuesday, March 25th, 2008

Ever needed to be able to generate random, but valid JavaScript code? Well, today is your lucky day: meet J.J. or JoJo, the Javascript Junk code generator.

All you need to specify is how many kilobytes of code you need. Available also as a web service.

» tools.w3clubs.com/jojo

If anyone can think of any application of JoJo, other than performance experiments, I'll be most intrigued to hear it.

 

sleep() in JavaScript

Monday, March 24th, 2008

PHP has a sleep() function, but JavaScript doesn't. Well, this is because it's useless, you might say, and you'll be right. But for simulating heavy processing and for misc performance measurements, it could be useful. So here's how you can go about creating a sleep() in JavaScript.

The code

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

Usage

Sleep for 1 second (1000 milliseconds):

console.log(new Date());
console.log('Dude!');
sleep(1000);
console.log(new Date());

Result in Firebug's console:

sleep.png

 

PHP-style $GLOBALS in Javascript?

Saturday, March 8th, 2008

Javascript has implied globals. When you skip the var in var a = 1; and go a = 1;, then a becomes a global variable. Some consider this an error in the language. Global variables should be avoided because they tend to overwrite each other in unexpected places, especially if the project grows in LOC and number of developers.

In PHP on the other hand, variables are local. If you need a global variable, then you have to have to be explicit about it using the $GLOBALS superglobal array.

So how about this: adopt the $GLOBALS convention in your JavaScripts? At the top of the script you go:

$GLOBALS = {};

Then every time you need a global variable, you do:

$GLOBALS['myglob'] = 1; // very PHP-like

or if you prefer:

$GLOBALS.myglob = 1;

Benefits of the approach:

  • global variables easy to spot (even from an aeroplane)
  • if it's not $GLOBAL, it's meant to be local. If it's missing the var, it's an error

Drawback:

  • It's a convention, so it can only help, but not enforce any coding practices

How many globals

Here's a quick test to check how many globals you have in a page.

(function(){
  var globs = 0;
  for (var i in window){
    globs++;
  }
  alert(globs);
})()

Run this script in your page without the scripts. Then add the scripts to the page run again. The result should be only one more global var if you followed the $GLOBALS convention.

 

Canvas pie with tooltips

Saturday, March 8th, 2008

This is very flattering: Greg Houston took my script for DIY canvas pie and added tooltips and better colors logic. Here's the result, it's really nice, built with some MooTools. The tooltips are not supported in <canvas> but Creg used an image that overlays the pie and set the tooltips with an image map. Clever, isn't it?

I just used random colors for the pieces of the pie, but Greg knows better. Based on a tutorial by Jim Bumgardner, he was able to achieve much more pleasing, yet reliable results. Funny thing that Jim works in Yahoo! two floors above me (used to be even on the same floor).

Check the demo and the post, cool stuff, works in IE too!

 

replace selected text (Firefox)

Thursday, March 6th, 2008

A quick function to replace the selected text (in Firefox). Accepts:

  • string to replace the selection, or
  • callback function that takes the selected text and returns a string to replace the selection
function replaceSelection(t) {
  if (typeof t === 'function') {
    t = t(window.getSelection().toString());
  }
  var range = window.getSelection().getRangeAt(0);
  range.deleteContents();
  range.insertNode(document.createTextNode(t));
}

Usage:

1. Replace selected text with "dude"
replaceSelection('dude');
2. Uppercase the selected text
replaceSelection(function(s){return s.toUpperCase()});
3. Lowercase the selected text
replaceSelection(function(s){return s.toLowerCase()});

Luckily I'm so close (and yet so far) to finishing this book, otherwise I won't be able to help myself but create a whole toolbar of bookmarklets for "power" Google doc users...

 

Canvas pie

Tuesday, February 5th, 2008

UPDATE: Translation in Brazilian Portuguese here, thanks Maujor!

OK, so you have an HTML table. Let's turn it into a pie chart with a bit of javascript.

We'll be using the canvas tag, so the browser has to support it. For IE - well, you still have the table. That's why we'll call it progressive enhancement. Unobtrusive too. Here's a screenshot:
canvas-pie.png

» The demo is here (refresh for new colors)

Here are the ingredients to the recipe:

  1. One <canvas> tag
  2. One <table> full of data
  3. javascript to get the data from the table
  4. javascript to plot the data on the canvas

One canvas tag

<canvas id="canvas" width="300" height="300"></canvas>

One table full of data

This is a bare bone unstyled old school table.

<table id="mydata">
    <tr>       <th>Lang</th><th>Value</th> </tr>
    <tr><td>JavaScript</td>  <td>100</td>  </tr>
    <tr><td>       CSS</td>  <td>200</td>  </tr>
    <tr><td>      HTML</td>  <td>300</td>  </tr>
    <tr><td>       PHP</td>  <td> 50</td>  </tr>
    <tr><td>     MySQL</td>  <td> 30</td>  </tr>
    <tr><td>    Apache</td>  <td> 10</td>  </tr>
    <tr><td>     Linux</td>  <td> 30</td>  </tr>
</table>

javascript to get the data from the table

First, some setup. Let's tell the script which is the ID of the data table, the ID of the canvas tag and which column contains the data:

// source data table and canvas tag
var data_table = document.getElementById('mydata');
var canvas = document.getElementById('canvas');
var td_index = 1; // which TD contains the data

Next, select all table rows, then loop through the rows, selecting all TDs. Add the data we need to a data array. While at it, run a total of the data in the column and also create an array of random colors. Paint each row with the selected color. (we'll see the actual getColor() in a bit.)

var tds, data = [], color, colors = [], value = 0, total = 0;
var trs = data_table.getElementsByTagName('tr'); // all TRs
for (var i = 0; i < trs.length; i++) {
    tds = trs[i].getElementsByTagName('td'); // all TDs

    if (tds.length === 0) continue; //  no TDs here, move on

    // get the value, update total
    value  = parseFloat(tds[td_index].innerHTML);
    data[data.length] = value;
    total += value;

    // random color
    color = getColor();
    colors[colors.length] = color; // save for later
    trs[i].style.backgroundColor = color; // color this TR
}

javascript to plot the data on the canvas

Time for the fun part, the drawing! First, we need to create a context object. Then figure out the raduis of the pie and the center, all based on the width/height pf the canvas tag:

// get canvas context, determine radius and center
var ctx = canvas.getContext('2d');
var canvas_size = [canvas.width, canvas.height];
var radius = Math.min(canvas_size[0], canvas_size[1]) / 2;
var center = [canvas_size[0]/2, canvas_size[1]/2];

Next, let's loop through data and paint pieces of the pie. To draw a piece of pie, you basically need to call these methods of the context object:

  • beginPath() - to start the piece of the pie
  • moveTo() - to set the pencil in the center
  • arc() - draw a piece of a circle
  • lineTo() - finish the circle piece with a line back to the center
  • closePath() and fill() but set the fill color first.

Here's the actual code for this part, hopefully the comments help:

var sofar = 0; // keep track of progress
// loop the data[]
for (var piece in data) {

    var thisvalue = data[piece] / total;

    ctx.beginPath();
    ctx.moveTo(center[0], center[1]); // center of the pie
    ctx.arc(  // draw next arc
        center[0],
        center[1],
        radius,
        Math.PI * (- 0.5 + 2 * sofar), // -0.5 sets set the start to be top
        Math.PI * (- 0.5 + 2 * (sofar + thisvalue)),
        false
    );

    ctx.lineTo(center[0], center[1]); // line back to the center
    ctx.closePath();
    ctx.fillStyle = colors[piece];    // color
    ctx.fill();

    sofar += thisvalue; // increment progress tracker
}

utility

Here's the function that gives a random color:

    // utility - generates random color
    function getColor() {
        var rgb = [];
        for (var i = 0; i < 3; i++) {
            rgb[i] = Math.round(100 * Math.random() + 155) ; // [155-255] = lighter colors
        }
        return 'rgb(' + rgb.join(',') + ')';
    }

C'est tout! Enjoy your pie :D

UPDATE: Comment by Zoltan below, if you use Explorer Canvas, you can make this work in IE with only this:
<!--[if IE]><script type="text/javascript"
src="/path/to/excanvas.js"></script><![endif]-->

 

MP3 player from Yahoo! - bookmarklet

Wednesday, January 23rd, 2008

Update Jan 30, 2008: updated code based on comments and code from Carl
Update Dec 11, 2008: updated the code thanks to the comment from Nolan

Here's the scenario: you have a page that links to some .mp3 files. You add a line of code in your page and lo and behold, there's a nice media player embedded into the page. Your visitors no longer have to download the MP3s, they can just stream it right there. All the mp3s on the page become part of a playlist.

The line in question you need to add to your page is:

<script src = "http://mediaplayer.yahoo.com/js"></script>

More about the player here - yahoomediaplayer.wikia.com

For examples of sites using this player in the wild, try aurgasm.us

A bookmarklet

Now, here's what you can do if you want to use the player, but the web site owner haven't incorporated it yet. Take the player with you. Run my bookmarklet that will simply insert the required javascript into the page.

So here goes in two easy steps:

  1. Grab the bookmarklet:

    Right-click, add to favorites

  2. Go to any page that links to MP3s and click your new shiny bookmarklet

    Enjoy!

Source

The readable source code of the bookmarklet:

javascript:(function(){

  var start = function(){YAHOO.mediaplayer.loadPlayerScript()};

  var script = document.createElement('script');
  script.src = 'http://mediaplayer.yahoo.com/js';

  if(script.addEventListener){
    script.addEventListener("load", start, false);
  } else{
    script.onreadystatechange = function(){
      if(this.readyState=="complete"){
        start();
        script = null;
      }
    }
  }
  script.type="text/javascript";
  document.getElementsByTagName('head')[0].appendChild(script);

})();
 

YUI pie chart example

Wednesday, January 16th, 2008

If case you haven't noticed - YUI Charts hit the streets.

As with everything new, it's best shown and understood by example. So here's the simplest example of using a pie chart. Basically I took the example from the YUI page, changed all the paths to point to yahooapis.com (where YUI is hosted for free) and stripped everything that could be stripped (there's even no html or head tags, but turned out the body tag is required). The result is a short html with all dependencies satisfied.

OK, so here's the example, grab, paste, customize:
chart.html

 

Table to chart via JavaScript

Tuesday, January 8th, 2008

A javascript by Christian Heilmann that takes a table from your page and constructs the URL to request a chart from Google APIs. Slick and accessible. Check it out.

 

Netflix - how many movies you’ve rented

Sunday, December 30th, 2007

Netflix is a great service, it's a shame they don't seem to provide any APIs. Oh, well, we'll have to resort to other means of extracting data.

A little javascript to count how many movies you've rented:

document
    .getElementById('returned_movies')
    .getElementsByTagName('tbody')[0]
    .getElementsByTagName('tr')
    .length

You can put this code in a bookmarklet or simply type in the Firebug console.

As people say "your markup is your API".

 

Fancy formatting

Friday, December 21st, 2007

Writing readable code means proper indentation. Usually you'd tab (or use 2 or 4 or 3 spaces) after every curly bracket. Something like this:

if (true) {
    // indent
    if (false) {
        // another indent
        // and some more
    }
}

Same goes when you have a bigger hash/object sort of thing:

var memememe = {
    name: 'Stoyan',
    family_name: 'Stefanov',
    blog: 'http://www.phpied.com',
    kids_count: 2,
    books_count: 3,
    occupation: 'programmer'
}

Sometimes I find myself going a little fancy and aligning all the values in the name/value pairs:

var memememe = {
    name:        'Stoyan',
    family_name: 'Stefanov',
    blog:        'http://www.phpied.com',
    kids_count:  2,
    books_count: 3,
    occupation:  'programmer'
}

But recently, inspired by Firebug's Net panel way of presenting header information, I tried aligning the keys to the right in addition to aligning the values to the left. So I ended up with something like this:

var memememe = {
          name: 'Stoyan',
   family_name: 'Stefanov',
          blog: 'http://www.phpied.com',
    kids_count: 2,
   books_count: 3,
    occupation: 'programmer'
}

Fancy, eh? I liked the way it looks. But then I thought that when writing maintainable code, anything fancy suggests uncommon, uncommon suggests that other team members won't be using it, so it means breaking the rule #1 of writing maintainable code: be predictable. (this also happens to be rule #1 of other common activities, such as driving on the highway and designing usable web sites)

This type of formatting is also not easy to type in an editor, so it will require a little more effort. Those two drawbacks are enough, I believe, to dismiss this idea. But I can't help myself liking the way the code looks. Here's a piece of PHP, which looks even better than javascript, because even more characters are centered.

<?php
$memememe = array(
          'name' => 'Stoyan',
   'family_name' => 'Stefanov',
          'blog' => 'http://www.phpied.com',
    'kids_count' => 2,
   'books_count' => 3,
    'occupation' => 'programmer'
);
?>

Ain't that cool?