i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

Better ways to writing JavaScript

Let me say it up front before you read the rest of this. This article is for beginners. This past week I decided to get involved with support requests in development forums for the sake of giving back (and it being close to Christmas time). I particularly cruised the Sitepoint JavaScript forum quite a bit and time and time again, I see the same mistakes plastered over code examples. That's quite alright, people are learning. I made the same mistakes when I first started. Nevertheless there are inevitably an infinite number of things you shouldn't be doing in JavaScript, but here are most common.

Stop writing document.getElementById

Really. If you can spot the string 'document.getElementById' more than once in your code, it should be pulled into a function. Even a basic getter like this:

getElementById Fetcher

function get(el) {

  return document.getElementById(el);

}
Most will even prefer the classic Prototype $ function that allows you to pass in an arbitrary number of arguments. That works well too.

Prototype $

$('foo', 'bar', 'baz');

Abstract your event attachment

Really. Get an addEvent function. There are literally hundreds. Pick one. I wrote one a few years back. Or even use an event utility. But really. It comes down to this:

addEvent simple

var addEvent = function() {

  if (window.addEventListener) {

    return function(el, type, fn) {

      el.addEventListener(type, fn, false);

    };

  } else if (window.attachEvent) {

    return function(el, type, fn) {

      var f = function() {

        fn.call(el, window.event);

      };

      el.attachEvent('on' + type, f);

    };

  }

}();

addEvent usagee

addEvent(get('example'), 'click', function(e) {

  alert('hello world');

});

Toggling is easy

By far the biggest behavior interaction request is how to toggle elements. Again, this all comes down to abstraction. Take advantage of making functions that are agile and flexible. Don't make dependencies on particular id's are. For example, here is a bad implementation:

bad toggling

function toggle() {

  if (document.getElementById('example').style == 'none') {

    document.getElementById('example').style = 'block';

  } else {

    document.getElementById('example').style = 'none';

  }

}

document.getElementById('toggler').onclick = toggle;

Here's how you might want to change things up a bit.

Better toggling

function toggle() {

  for (var i=0, el; el = get(arguments[i]); i++) {

    el.style.display = (el.style.display != 'none' ? 'none' : '' );

  }

}

addEvent(get('toggler'), 'click', function() {

  toggle('example');

  // heck, do more!

  toggle('foo', 'bar', 'baz', 'thunk');

});

AJAX

Making AJAX style applications is much easier than you think. The key (again) is coming up with a simple interface to calling these requests. The first thing you'll need is an asyncRequest function. As well, I wrote one of these just a bit ago. It works like this:

send requests

asyncRequest('GET', 'test.php?foo=bar', callback);

function callback(o) {

  alert(o.responseText);

}

test.php

<?php

  // test.php

  echo 'you sent ' . $_GET['foo'];

?>
What this does is sends a 'GET' request to test.php. In return, test.php echo's you sent bar. A response is sent to the callback function, and we access its responseText property. That, my friends, is how AJAX works.

Changing Styles

Every DOM element has a style object associated with itself. This is how you see things change on the fly on any given webpage. For example, once you have an element reference (via the get function as previously mentioned on this article), you can change its style's by simply doing the following:

changing styles on an element

var element = get('example');

element.style.color = 'red';

element.style.fontSize = '2em';
If you wanted to, you could create a simple function that changed the style of an element, for instance, it's color. And since JavaScript has First-class functions built into the language, we can use a simple curried style function that can be attached to event listeners. This means that functions can take in arguments, and pass them along to another returned inner function.

changing color

function changeColor(color) {

  return function() {

    this.style.color = color;

  };

}

addEvent(get('example'), 'click', changeColor('blue'));

Cheers, and happy December!

this is who i am

Hi, my name is Dustin Diaz and I'm an Engineer @ObviousCorp. Previously @Twitter, @Google, and @Yahoo, author of Strobist® Info co-author of JavaScript Design Patterns, co-creator of the Ender JavaScript Framework, a Photographer, and an amateur Mixologist. This is my website. Welcome!

On this site I write about JavaScript. You can also follow along with my open-source work on Github.

This site is optimized and works best in Microsoft Internet Explorer 6.