No Mod Required

Archive for the 'javascript' Category

No wonder they contacted me all the way from Cali…

Yahoo! is training front end developers to fill their staffing needs…

The Harvard Of JavaScript Training (Yahoo! Developer Network blog)

When you think of prestigious law schools, it’s Harvard. Computer Science? Maybe MIT or Carnegie Mellon. When it comes to front end engineering though, Yahoo! Juku may be the best bet. Taught largely by our in-house front end pros, including YUI developers Nate Koechley, Yahoo! Juku Nicholas Zakas, and Thomas Sha, and JSON inventor Doug Crockford, Yahoo! Juku is a comprehensive, 3-6 month program to train professional front end developers. The curriculum includes advanced topics in JavaScript, DOM, HTML, CSS, YUI, performance, and accessibility.

Why train raw recruits to this degree? Well, in the San Francisco Bay Area, including the Silicon Valley, it’s hard-as-heck to find good front end programmers and web designers. Things aren’t as crazy as in 1999, when many companies seemed to grab random people off the street to do front end development, but top talent is still scarce. The first class of 13 Juku graduates will toss their hats into the air on December 14th!

Dear Yahoo! You don’t need to go to all that trouble… just open a Boston office or let me telecommute and I’m all yours! I’ll even give up “Plain Old JavaScript” and hitch my wagon to YUI full time! That’s dedication.

Books 2007 #14 PPK on JavaScript

ppk on JavaScript, 1/e (VOICES) Another excellent introductory book. I got this mostly as a way of thanking Pete Paul Koch for all of his invaluable work over the years at quirksmode.org, but reading it was still a worthy way to spend my time. Not surprisingly (since he knows his stuff backwards and forwards) it’s an excellent book, well written, easy to follow and very thorough. I’m going to recommend it going forward to anyone looking for an introduction to JavaScript programming.

Automatically Track Outgoing Links in Google Analytics with Javascript

I’m currently reading the O’Reilly Google Analytics book, so of course I’m going to sandbox some stuff (albeit not here at this site.) One of the first things I seized on was the ability to track outgoing links by calling the urchinTracker() function onclick. Taking a few minutes out of my morning I put this together:

//window.onload we run this
var anchors=document.getElementsByTagName("a");
for (i=0;i<anchors.length;i++) {
    anchors[i].onclick=trackOutBoundLinks;
}

the trackOutBoundLinks function looks like this:

function trackOutBoundLinks(){
var thelink=this.href;
if (thelink.indexOf(location.hostname) ==-1 ){
   urchinTracker('outgoing:'+thelink+'');
   document.location.href=''+thelink+'';
   return false;;
   }
}

And with that you get fancy entries in your content list like this:

"/outgoing:http://www.dccomics.com/graphic_novels/?gn=7679"

Of course, the above will skew your page views, etc. so you’ll need to apply some filters and/or create a new profile, if you want to track page views in the default way in addition to tracking outgoing links, etc. but all that’s a Google Analytics matter*. The biggest JavaScript caveat is that if you’ve got any other onclick events on your anchor tags the above will muck with them. But if not, it’s that simple to start tracking outgoing links. Pretty cool, I think.

Here’s a zip file with a small script file that will insert the above into any page it’s attached to. I might write a more generic version of this that will work in any environment if I get the time, but for now if people are interested here it is to play around with. Simply upload the analytics.js to your server and attach it to the page in question and it should work:

<script src="/your-path-to/analytics.js" type="text/javascript"></script>

*albeit a pretty big one. I can’t stress enough that this code will completely skew your content reports. You need to have two profiles- one which filters against outgoing: and one which doesn’t. The one which does will track page views in the normal way, the one that doesn’t will have all the fancy outgoing links interspersed with the content reports. I am not savvy enough with analytics to solidly answer questions about that side of this business, so if you’re unsure look to some Google Analytics expert for sage advice on the ins and outs of profiles and filters. Maybe after reading the rest of this book and sandboxing these techniques for a month or two I’ll be more certain about some of these things, but for now I’m a javascript nerd who’s just exploring the GA landscape.

The difference between javascript’s getElementById() and getElementsByName()

The above question is one I’ve gotten in my logs a couple of times. I don’t actually answer it anywhere on the site, so I figured I might as well answer it here. For some strange reason, in my mellowed old age, I’m all about helping and I haven’t written about web technologies in about a month, so it can’t hurt.

The basic answer is this-

  • getElementById() is incredibly useful. If you write any JavaScript at all, you’ll likely use it all the time
  • getElementsByName() isn’t really useful at all. I’ve never used it ever and can’t really think of a place where I would use it. I rarely use the name attribute and can’t really see where I would want to use it in any way that would make sense in the context of this method.

To define them, the specs say

getElementsByName
With HTML 4.01 documents, this method returns the (possibly empty) collection of elements whose name value is given by elementName (The name attribute value for an element.) In [XHTML 1.0] documents, this methods only return the (possibly empty) collection of form controls with matching name. This method is case sensitive.

Which is to say you pass the method a string (the name) and you get back a nodeList , a collection of elements with matching that name.

Which is, as far as my experience goes, a big pile of useless.*

getElementById
Returns the Element whose ID is given by elementId. If no such element exists, returns null. Behavior is not defined if more than one element has this ID.

Which means- pass this method a string (the id) and this method will return either an element matching that id or null. This is probably one of the most used DOM methods in the Javascript universe. Accessing and manipulating elements is what JavaScript is all about and getElementById is the handiest method for accessing an individual element on a page.

*which isn’t to say I don’t want to hear about a really cool use of it if there’s one out there. If you’ve got one, please share! I love seeing interesting code samples :)

The Wii Remote API posted by Opera…. and then (mysteriously?) pulled

I had this link to The Wii Remote API saved in my Reddit feed on Bloglines for a few days, waiting for just the right moment to crack open the link and check out the keys to some hot Wiimote magic. Clicking through- it’s all blank page and “access denied.” Oh no! Completely confused, I started poking around and caught this thread on their forums where people are all five flavors of “wha?!” about the fact that the article was pulled. Me, I’ve decided to work on the world’s greatest conspiracy theory to explain why it was pulled. It will involve crazed terrorists, a man dressed in a foam Mario suit, Wii Sports, fifteen pounds of peanuts, Satoru Iwata, and a large albino African elephant. If my conspiracy theory were to be made into a movie, I would want Angelo Badalamenti to write the soundtrack, but I would force him to rework the songs of John Philip Sousa.

Thankfully I was able to save the mirrored document. In theory I could actually have real, business use for some Wii-More scripting knowledge. How often does that happen? a real business case for using perversely bleeding edge technology? Never.

JSON Feeds For Fun and Profit Part 2 - Callbacks with Twitter

In my first exploration of the JSON data interchange format, I used it in its most basic way possible. I attached a script (from delicious) to a page and simply used the built-in object created by their implementation to generate an unordered list of my recent del.icio.us posts. While it showed how easy it is to use the O, a handy, structured, Javascript Object, provided by JSON, it didn’t really illustrate how to manipulate the page with new data after page load. That is, after all, a very now thing to do, so it’s kind of important. This article will examine how to dynamically load a JSON feed and how to get data out into a usable form using a callback.

While one can load JSON using XMLHttpRequests, the real benefit of JSON is to be able to load data from a third party without worrying about the browser security model and without having to rely on a local pass through file. So, we’re going to load the data without XHR in this example. Instead we’re going to load it using dynamic script tags.

Here’s the function I’m using in my example:

function twitter_me() {
   var twitter_JSON = document.createElement("script");
   twitter_JSON.type="text/javascript"
   twitter_JSON.src="http://twitter.com/statuses/user_timeline/rob_react.json?callback=twitter_callback&count=10"
   document.getElementsByTagName("head")[0].appendChild(twitter_JSON);
}

First I create a new script element in the document, then I set the type and source. The source is the interesting part. As you can see, after the URL for the JSON document representing my twitter updates, I append a query string. The first argument for that query string (callback=twitter_callback) is where the magic happens. There I’m defining the function that will be called when the script is attached to the document. To see what happens compare the first few characters of the JSON script called with and without the callback.

Here it is, as referenced in the above code

twitter_callback([{"source":"web","text":"426 queries in 107.66 milliseconds. drupal is teh awesome",

and called without the callback (but with the count, so the data structure returned is the same)

[{"source":"web","text":"426 queries in 107.66 milliseconds. drupal is teh awesome",

Notice the function referenced in the first example. Right there, as soon as the JSON document is loaded, JavaScript executing the callback function with the JSON object as an argument. I'm a JavaScript geek and all, so I'm biased... but that's just plain cool.

So what happens next, you ask? Well, since I defined a function called twitter_callback, that function is run and I'm able to do all sorts of cool things with the provided object. Here's the function in all its glory:


function twitter_callback(twit) {

 //this is the div I'm writing the content to
 var t_div = document.getElementById("twitter");

//these are some other variables, mostly
 //placeholders so that the code is a little clearer
 var who,what,when,icon, bgcolor

//start the ul
 t_div.innerHTML = "<ul>"

   //loop through the twit object
   for (i=0;i<twit.length;i++) {

   //Look at me use the JavaScript modulus operator to do even/odd rows.
   if(i % 2) {
      bgcolor="#efefef"
   } else {
      bgcolor="#ddd"
   }

   //Right here, I've broken out the separate bits of the string into placeholder variables
   //so you can more easily see the dot notation and array indices in place
   //once you figure out the structure it's dead easy to reference data in an Object
   icon=twit[i].user.profile_image_url;
   who=twit[i].user.name;
   what=twit[i].text;
   when=twit[i].created_at.substr(0,19);

   //and here I mash it all up into a fancy li
   t_div.innerHTML +="<li style=’background:"+bgcolor+" url("+icon+") no-repeat’><strong>"+who+"</strong>: "+what+" ("+when+" GMT) </li>"
   }
  //and close the UL
  t_div.innerHTML += "</ul>"
}

Here it is in action (be patient, Twitter can be slow):

Call me crazy, but that’s something like 75% away from being a widget and there are no cross domain concerns to deal with so it could easily be spread far and wide. There’s a lot to like right there :)

That’s it for this time. Feel free to ping me with questions or comments.

Next up, as I mentioned, one can load JSON via XMLHttpRequest, so I’ll be building an example that does just that. There’s a wrinkle tossed in with that technique that will make things, if not tougher, a little less cool (eval(), I’m looking in your direction.) More on that when I put it all together.

JSON Feeds For Fun and Profit, Part One- Del.icio.us makes it easy

Confession time: I’ve never actually worked with a JSON feed.

No, really.

I know what you’re thinking… Yes, you’re right. I’ve built a bunch of Ajax-y components and one full blown application over the past two years.

No, in light of that it doesn’t make any sense that I haven’t used JSON before.

Anyway, I’ve been helping out one of our developers at work with My Big Javascript Brain™ and I’ve had to mess about with JSON a little bit. She’s ostensibly a Java developer, but she’s shown a willingness to help out wherever she can (thereby learning a bunch of other web technologies,) so this week she’s been tasked with creating a JSON fed Google widget. This has been interesting for me, as I’ve had to guess a lot and leap at solutions at every turn to try to help her (since I have no practical experience with the acronym myself.) The good thing is I’ve actually been helpful. Apparently I’ve soaked up enough about JSON through osmosis or something, because when that feeble amount was blended with my regular JS knowledge I was actually able to piece together some of what was going on. Go me.

Anyway, to actually know what I’m doing the next time, I’ve decided to play around with some feeds right here and write up what I discover to help solidify my own knowledge and to help out anyone else who might be wondering about the magical world of JSON feeds.

Did I mention that they were magical? They are. They’re made of pixie dust and rainbows.

Yes, I’ve gone slightly off the rails… ignore that last bit.

To start with, I decided to use the handy feed from one of my favorite web twenty web sites, del.icio.us. Not surprisingly, since del.icio.us kicks all kinds of ass, they make it dead easy to use JSON feeds. All it takes is attaching the script generated at http://del.icio.us/feeds/json/user_name to a document and a Delicious JavaScript object is automatically created- full of all sorts of social bookmarking goodness. Notably a posts array which contains all of the selected user’s posts.

You can read their concise documentation here. They have a nifty sample as well.

Here’s the example I whipped up. This grabs the last 15 bookmarks from my account, takes the link, description and tags and drops them all into a regular old unordered list*.

Here’s the feed itself. As you can see it contains a simple test to see if the Object already exists, an object definition and then an array populated with all of the post data. Pretty straightforward, really.

The following code sample shows how I did it. My comments are inline and in blue.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>JSON part 1</title>

<!--Seriously. This is all it takes to get the object into your document. 
That's really cool, right? I think so-->
<script type="text/javascript" src="http://del.icio.us/feeds/json/rob_react"></script>
<script type="text/javascript">
window.onload = function() {

//this is the built in delicious object. 
//the array posts has all the stuff we're looking for. 
//let's make a quick reference to it
var del = Delicious.posts;
var d_div = document.getElementById("delicious");

// create a placeholder for the link
var the_link=""

//****As a note, I've found writing out innerHTML 
//****to be faster, so I use it. 
//****I actually prefer the elegance of JavaScript's 
//****DOM based node creation and manipulation methods.
//**** but speed roolz, so I play with strings
//**** sometimes this stuff can get really confusing, 
//**** though, so I'll fall back and use
//**** the DOM stuff anyway. 
//**** Anyway, back to the script...

//write the beginning of the <UL>
d_div.innerHTML = "<ul>"

//loop through every element in the Delicious.posts object and do stuff
for (i=0;i<del.length;i++) {

//look at me, I'm doing stuff!
//clear the placeholder for the link
the_link="";

//  add in the opening of the LI and the opening of the anchor
// add a reference to the u (url) of the i member of the del array
// and the d (description) of the same memberr
the_link ="<li><a href='"+del[i].u+"'>"+del[i].d+"</a>";

//are there tags? is there a tags array of the i member?
if (del[i].t) {

//if so lets write them out
the_link +=" <em>tags:</em> "

//loop through all the mambers of the t (tag) array
for (j=0;j<del[i].t.length;j++) {

//and build another link
//here I'm using the simple, but powerful URL scheme
//that delicious uses to nice effect
//by dropping the the tag onto the end of my delicious url
//I'm easily building out links to my tags
//they use a logical, transparent url scheme which makes 
//it crazy easy to navigate both as a user and as a programmer
//go delicious go.
the_link +="[ <a href='http://del.icio.us/rob_react/"+del[i].t[j]+"'>"+del[i].t[j] +"</a> ]" 
}
}

//close out the li
the_link += "</li>"

//pop that link and li into the div
d_div.innerHTML += the_link
}

 //once the loop is done, close the ul
d_div.innerHTML += "</ul>"

//and that's that. like I said, pure magic.
}
</script>
<style type="text/css">

/*I've got style*/
body {
color:#666;

/*by the way, shorthand is your friend!*/
font: .825em/1.8em Verdana, Arial, Helvetica, sans-serif;
}
em {
color:green;
margin-left:10px;
}
</style>
</head>
<body>
<div id="delicious">
</div>
</body>
</html>

And that’s that- a run-through of the simplest possible usage of a JSON feed (at least in terms of extracting the data.) Next time (which should be soon) I’ll look at different methods for getting dynamic data out of JSON. Oh, the fun we’ll have.

(part 2 of this series | part 3 of this series)

*The note is also available- I’ll use that in my next example.

I’m not sure I’d jump to pay money for TypePad after witnessing this:

I was browsing the TypePad Blog and Blogging Comparison Chart (not that I’m thinking of switching, it was just for work,) when one of my co-workers pointed out the rapidly growing firebug error count in the lower right corner. By the time I looked it had grown to well over 4000 errors. It seems like someone over there doesn’t quite know how to use jquery? I’m sure it’s something simple, but that doesn’t mean it won’t potentially hurt their chances to sell their pay blogging platform*.

4295-errors.jpg

Click for the full screen shot.

someones-made-a-boo-boo

*Although I wonder how much it would actually effect them? What are the demographics of someone who would go for a pay blogging platform? Would they be technical enough to notice JavaScript errors (especially in that abundance) and recognize them as a potential problem? Or would anyone looking for a pay solution be going to it because it presumably offers some level of real technical support? Anyone know?

I also wonder how long it’s been broken.

Answering Google- Passing a Random Number to a Div id in Javascript

Occasionally I see specific searches that bring people to my site and I wonder if people actually found the answers they were looking for in my code articles. Sometimes I think they probably did, but sometimes I’m not so sure. So… I figured why not answer some of the more interesting pleas directly? Lord knows if anyone will ever need to do such a thing again, but if they do I’ll be ready for them (and I get to problem solve in public :) )

Anyway, here’s one that I thought was interesting. The exact search was:

how to pass random no to div id in javascript

The first result points to this site, but I’m almost certain the article it points to won’t be of any help.

This function would be of great help

function random_div_id(obj) {
//obj is the div to be randomized
//get a random integer between 1 and 10000
     rand_id = parseInt(Math.random()*10000);
//concatenate the old id, a dash and the random number into a new random id
//if you wanted, you could just pass the rand_id and be done with it.
     obj.setAttribute("id",obj.id+"-"+rand_id);
}
 

Here’s an example:

A static variation on JavaScript’s getElementsByTagName

As I mentioned yesterday I wanted to offer up an alternative to the browser crushing example I made to illustrate the point about Javascript Objects. So here it is…

Instead of using getElementsByTagName("a") and watching the count grow towards infinity, I simply added a new function which does the same thing as getElementsByTagName, except that it takes a "snapshot" of the nodeList and turns it into a plain old Array. So, unlike a variable created with getElementsByTagName, this one will not track changes to the underlying DOM collection.* I’ve illustrated this with a count of the members of the two collections before and after the manipulations are run.

Here’s a sample:

And here’s the function

function getStaticCollectionByTagName(tag, node) {
  //just like getElementsByTagName, we want to open up and optional context node 
  if (node==undefined) {
  //if it's not passed in as an argument, we set it to be document 
  node=document
  }
  //we build a variable with the original collection 
  var temp_array = node.getElementsByTagName(tag);
  //and a new array to hold them 
  var static_results = new Array;
  //then we just loop through and copy each into the new array 
  for (i=0; i<temp_array.length;i++) {
  static_results.push(temp_array[i]);
  }
  //and return it 
  return static_results;
  }

As a note, feel free to comment on any/all of the code articles I write here. I’m mostly writing this stuff to push my own knowledge and understanding so if you see something I can do better, something that I’ve missed or something that’s just plain silly, feel free to let me know :)

*it WILL track the individual objects that make up the collection as those are passed to the new array as Object references.