with Imagination: by Dustin Diaz

./with Imagination

A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

Better ways to writing JavaScript

Saturday, December 1st, 2007

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!

65 Responses to “Better ways to writing JavaScript”

  1. David Golightly

    Urf! I would steer clear from advising beginners to set anything on the “style” property of an element. Better to add/remove class name and define the properties themselves in CSS, where they belong. Anything else sends a mixed message about semantic markup and inline styles.

  2. Dustin Diaz

    David, there is a reason the style object API exists. Hence another reason I feel indifferent about inline styles on scrict doctypes. Nevertheless, you do have a general purpose point about setting class names in with JavaScript, which is largely more helpful when you’re setting a heap of styles. I don’t think anywhere here is going to get the wrong impression.

  3. Dean

    Due to bugs in IE, I would advise using a “corrected ” version of getElementById()

    e.g.
    http://webbugtrack.blogspot.com/2007/08/bug-152-getelementbyid-returns.html

    Likewise, the toggle, should do a quick node check to see if it is a table row or not, whereby if it is, should toggle between “” (blank), and “table-row”.

  4. Dustin Diaz

    Hi Dean,
    I wonder how many people actually run into that bug with getElementById. It’s used in practically every JavaScript library, and 99.99% of the time, it will be used correctly. Therefore, I would personally not advice a workaround for such a mundane bug.

    However regarding the toggle, you’ll also notice that I did not use ‘block’ for the display. It’s simply ‘none’ or whatever the display is by default. For example when the display is set to “” (blank) on a table row, it will know inherently to have a display of table-row (same goes for table, and table-cell).

  5. Stuart Langridge

    Why wrap document.getElementById? It doesn’t seem to make the code much clearer, to me (on the contrary, if you’re inexperienced then it’s one new function you have to look up in the code to work out what it’s doing).

  6. Dustin Diaz

    Sil: Haha. are you serious? To me (personally) there’s nothing worse than seeing a plague of document.getElementById’s.

  7. Fran5ois

    I have the same question than Stuart and your answer is not an answer. Could you explain a little more why is there nothing worse than seeing a plague of document.getElementById’s ?

  8. Allan

    I don’t get why would you want to wrap document.getElementById either. Is it just a personal code style, or is it to save a few characters? I’ve just done a quick test to compare the speed of using document.getElementById compared to a globally defined function (with only one other global function) and document.getElementById is faster. Not much - but it is consistent.

    Would you also advocate wrapping document.getElementsByTagName, Math.abs etc?

  9. Stuart Langridge

    Really? I think it looks clearer, myself, unless you’re already using a library anyway — I use jQuery for things, so $(”#elementid”) shows up, but then so does $(”#elementid > li:last”) and so on. In the absence of that, d.gEBId isn’t that much more verbose and it certainly *is* a lot clearer.

  10. Simon

    Although your samples for these things are ok, Would you seriously use rework to write your own ajax/dom manipulators when there are so many good libraries already!

    Regarding your toggle and other style attributes: I’d always suggest clean unobtrusive javascript. eg: Javascript for your toggle should add/remove classnames, not styles.

    Seperating code from styling is a much better practice.

    In fact most javascript libraries are so good, I don’t actually know why you’d write your getters and setters for dom elements. It seems silly to me…

  11. Jesse Burcsik

    Wow, great article… Wondering what event or chain of events let to you writing this hate tutorial.
    Like the short cuts, thanks

  12. Be A Better JavaScripter! « FlashColony Blog

    [...] article for beginners on how to write a better JavaScript code and be a better programmer. It talks about a [...]

  13. Lim Chee Aun

    In ‘bad toggling’ example,
    document.getElementById('example').style = 'block'
    Huh? Is this correct?

  14. Marc

    Thanks for the basic tips, Dustin.

  15. Dustin Diaz

    Ok, since Allan also brought it up, I know it’s not just Stuart. I presume it’s just a preference in verboseness. This is yet another reason when I use YUI, the first variables I set look like this:

    var Y = YAHOO.util,
        Dom = Y.Dom,
        Event = Y.Event;

    So it only logically makes sense for what I do when getElementById. Nevertheless, we both sound like we’re nitpicking. In regards to Allan’s comment to wrapping other JavaScript methods - my main concern is about scripting the DOM - and by far the most common method used is document.getElementById.

    @Simon: This article isn’t about JavaScript libraries. I generally try and keep the trolls (not you, btw) out of threads that drop into certain scenarios with their jQuery answer that’s maybe a few lines long. Very rarely do people actually learn real JavaScript that way when you’re trying to help someone out. As much as I have for a knack for jQuery myself (heck, I even wrote a chaining library too), I think there’s value getting down to the basics and showing JavaScript from scratch.

    @Marc: Yes, that’s right. Remember, it’s a ‘bad’ example :)

  16. H5N1

    Mmmmm… in this way “beginners” are no more beginners… :)
    I don’t know why there’re so much confusion!
    “Separate script from styling”?
    Ok, it can be good if what I show is shown even without javascript!
    But, for example, in something like lightbox or similar, you don’t need it.
    If javascript is disabled = no style = no shown elements!
    Why I cannot style elements by javascript?

    @Simon: aright, there’s a lot (too many?) working framework and library, but writing by yourself it’s different!
    I like to code, that’s why.

    Thank you Dustin, maybe most of us just knew this “better ways” but maybe some other have to, yet!

    :)

  17. David Golightly

    Dustin - The “style” property is very useful for transition effects - accordions, fadein/fadeout, etc. It definitely has legitimate uses, as you point out in the article you linked to in your comment (inline styles in strict doctypes). The problem isn’t so much one of specifying attributes on nodes vs. in CSS, it’s a more general practice of keeping things semantic - eg., if it’s red, it’s red for a reason, and might need to be other things as well: have a red border, a certain backgroundImage icon, etc. What’s important is not that it’s red (a short-term goal that can get you into trouble), but that it indicates a semantic value (eg. “warning”), which is what JS should manipulate where possible for clarity and ease of manipulation. It’s the same reason why languages like C++/Java have a “const” keyword or otherwise assign constant values to identifiers - readability, maintainability, consistency. Otherwise, a great article! Keep up the good work.

  18. links for 2007-12-02 « AB’s reflections

    [...] Better ways to writing JavaScript (tags: javascript programming ajax tips tricks webdesign) [...]

  19. Phil

    Thanks Dustin, great tips that I’ll be putting to use soon.

    One question though, when you start a JavaScript project without a library like JQuery or Prototype, do you still have a set of utility functions, like your AJAX and event attacher from this article? I’d be interested to know what shortcuts and other useful functions you keep close to you at all times!

  20. Dustin Diaz

    Hi Phil, something like this pretty much sums it up for me for any sort of simple projects. Once you dive into making remote requests or animation, that’s where I draw the line and drop in a library like YUI, or Prototype.

  21. Chris Heilmann

    I don’t get it. On the one hand this is supposed to be “giving back” as it is soon Christmas time and then you argue with people on a personal level when they ask a very understandable question.

    As to the tips, this sounds like a mix of “write your own library” (do we need another one?) and “do this and it is right, believe me, I am the expert and you don’t want to know”.

    I, too disagree with telling beginners that style manipulation in JS is a good thing to do. Granted, it is great to explain JavaScript but it has no semantic value and it is a pain for maintenance. Not every JS developer needs to know all the things CSS can do and not every designer wants to edit JS to change the look and feel.

    Most of these examples are also completely out of context. The toggle example adds a click handler without overriding the default behaviour. If you were to use a link pointing to an anchor (which is a good, unobtrusive idea, especially in terms of accessibility) this would toggle and shift the page around, if you override a link pointing to a document it wouldn’t work. If you wanted to have the toggle trigger only when JS is available, you should create it with JS.

    The Ajax example is very dangerous. Ajax is not 5 lines of code, it is a complex user interaction that needs notifications that something happens and it also needs clever server side components. This example on a server would allow me to inject any JavaScript into the page which is a big security risk.

    It is a good idea to help people, but this is a mix of practices that might work for you, but need a lot more backup to become “better JavaScript”.

    I’d have expected more of you, as your book has some very nice ideas and you showed here that you do think of details.

  22. Caminews » Better ways to writing JavaScript

    [...] Fonte: http://www.dustindiaz.com/javascript-no-no/ [...]

  23. Dustin Diaz

    Hi Christian, (as well as sil), let me remind of what the first two sentences said:

    “Let me say it up front before you read the rest of this. This article is for beginners. ”

    With that in mind, it is just that. This is for beginners. You were expecting more? Any more would make it that much more complicated.

    Re: “‘write your own library’ (do we need another one?)” - Agreed. We don’t need another. And this was not about that.

    Re: “then you argue with people on a personal level when they ask a very understandable question.”

    And no point in my comments am I arguing with anyone. I do however backup what I write (as you should too (and you do)).

    Your comments (as one might call nitpicking) are completely irrelevant to the JavaScript novice. These are basic examples and ‘do’ in fact get the job done.

    Even if you were to rewrite my functions, or offer different approaches, my nitpicks would ‘as well’ be just as irrelevant. I am confident in your work, yet as we both have different styles, we both get the job done.

    Re: “I’d have expected more of you, as your book has some very nice ideas and you showed here that you do think of details.”

    Don’t buy the book. I’m already sending you a free copy.

  24. Brian

    I just can’t believe how many of you can complain about a perfectly acceptable tutorial like this one. What amazes me is when other developers criticize techniques like these that are extremely, extremely (did I mention extremely) common in almost any JavaScript library or book tutorial.

    I think you did a fine job with this one Dustin. Any beginner would find it very useful in learning JavaScript.

  25. Saif Khan

    Hi,
    When will this book be out? For Christmas you think?

  26. Dustin Diaz

    @Saif: The book is already available on Apress as an E-book. We are in fact expecting the printed version to be out sometime before Christmas (mid December).

  27. Chris Heilmann

    The fact that this *is* for beginners is why people critisize this tutorial. This is based on different views on how new developers learn JavaScript.

    This kind of tutorial is a “here is something that works - just use it”. When we founded the WaSP DOM Scripting Task Force in 2005, this is exactly what we were complaining about: people learnt JavaScript by copy and paste and not by seeing it in context.

    We are building more and more complex JavaScripts these days and managed to get it to turn from something that was laughable on your CV to one of the main technologies HR looks for in Web developers.

    Now I consider it time that we turn scripting into a real professional skill, not a “use this, don’t worry what it does”. This is what I talked about at @media Ajax and being aware of it makes you hireable for companies that care about quality and teamwork.

    Instead of explaining the how it is time to teach the how and the why. A lot of old-school JS developers learnt JavaScript from quick examples that did the trick and never bothered to understand what they do and how they fail. Only if you know the latter you’d be able to fix a bug or amend a script when it causes problems.

    Just giving examples that work actually is counterproductive in making people learn JavaScript. They shut down right after copying as the task is done: “I build a cool slider menu” instead of “I built this menu and I actually know how it works”.

  28. Dustin Diaz

    Chris, I’m not “building a slider menu” - I’m giving people advice on ‘how to’ build the slider menu. Simply implementing a menu, I would think, is *more* counter-productive.

    Re: “Just giving examples that work actually is counterproductive in making people learn JavaScript.”

    Are you suggesting I give examples that *don’t* work?

    Re: “We are building more and more complex JavaScripts these days”

    Again, this is not about complex JavaScript projects. These are not tools for building your next AJAX application that will take over the world. These tips are for people, who quite possibly, have never written JavaScript, or know fairly little.

    Besides, I think you’ll notice that most of the comments from the beginners were quite happy with the way it turned out. Quite frankly, I think you’ve blown this out of proportion more so than it needed to be. This wasn’t meant to be long or exhaustive, but rather a few simple tips for the beginner.

  29. Mark Johnson

    For the record, I’ve run into IE’s getElementById bug, years ago. It’s really worth coding around this if you’re a pro–because someone is going to have to maintain that code, and if someone triggers that bug by changing something elsewhere on the page… uh-oh. And it’s especially true for framework code, where defensive programming is even more important.

  30. Chris Heilmann

    You are being deliberately glib now and I am out of here. Two things:

    “These tips are for people, who quite possibly, have never written JavaScript, or know fairly little.”

    … so let’s make sure it stays that way?

    “Besides, I think you’ll notice that most of the comments from the beginners were quite happy with the way it turned out.”

    If you see your comments as a fair view of the world and a constructive criticism of your post then you forget all the people that read your RSS and dismiss it. It is NOT a measure of how good your post is - anymore.

  31. c.

    You don’t even give a reason, let alone a sound one, as to why you want people to use a wrapper around getElementById. You do that in any other language and your code ends up on the Daily WTF?

    By aliasing a method *everyone* is familiar with, you’re making it less readable to other programmers just for the sake of saving a few characters.

  32. Alan

    I am wondering about your advice to map document.getElementById to a shorthand method like $

    If one was to use prototype, does that not add a huge ammount of overhead since it extends the element and adds all the Prototype helpers?

    –Alan

  33. Jeff L

    Dustin,

    I think this post was written with good intentions, but I believe it’s hard for someone who is an expert in something to know what might be of great help to someone who is a beginner.

    As someone who is somewhat in the middle, I tend to agree there are some issues in this post as it would relate to true beginners.

    A few thoughts:

    Regarding your document.getElementById suggestion, I’d suggest that you might want to generalize a bit more. Rather than just suggesting someone should never use getElementById, it might be helpful to suggest that anytime someone needs to type the same text over and over again, it can probably be done better. Either by pulling into a function as you suggested (though I’m not sure why) or as you mentioned in your comments with your usage of Yahoo (var Y = YAHOO.Util;).

    In your toggle example, you not only made it better by not hard coded display type or ID, but you made it more confusing by throwing in some tertiary notation…do you expect a beginner to be familiar with that?

    And I even find your last example a bit confusing…

    I think overall it’s a great post but maybe not as geared towards beginners as you had intended.

  34. H5N1

    Dustin, Chris, I’m an “old” developer grown up with the old-school-CopyAndPaste practice but I can (as you, I suppose) remember when I started and all my mistakes.
    In the beginning, when you write (copy and paste) your code the only important thing is that it works. So you can write hundreds lines of code, no matter, but if it works it’s enough.
    Most of the beginners start with Internet Explorer (you know, it’s the most diffuse browser) and a part of ‘em neither knows that Firefox, Opera and Safari exist! How can they think about something like crossbrowsing?
    I think either that when we’re talking about “WaSP DOM Scripting Task Force” or “semantic sense” we are even talking of something not for beginners.
    Maybe I’m losing the real meaning of the whole context and I think it can be enough strt thinking at javascript just link an help for rich content or a “better navigation experience”.
    Reading your dialoge here it seems to me (linke here in Italy we say) that you’re talking the same language without understand yourself! :)
    It seems, in fact, that you’re talking about the same thing but with two different point of view.

    I don’t think (and don’t want to think) that Dustin want to appear as a “teacher” or a master, he only suggest a different way to face things.

    Sorry for my poor english, anyway. :)

  35. links for 2007-12-04 « Donghai Ma

    [...] Better ways to writing JavaScript (tags: javascript programming tips tutorial) [...]

  36. Tips de como mejorar nuestro codigo javascript | frogx.three

    [...] interesante post en base a un post de Mr. Justin Diaz con tips que el mismo justin recomienda para mejorar nuestra forma de programar con javascript y asi optimizar nuestro trabajo, muy buenos [...]

  37. Ray

    I am by no means an expert in JavaScript, I was educated in university in what I regard as the best use of C++, Java, .NET, a splash of JavaScript and basic HTML/CSS. Since completing my degree 2 years ago, I have bought various books to futher hone my scripting skills and teach myself the finer points of JS. At this stage in my development I would cite Dustins screencasts and code examples as something that has had a very positive step in my JS education.

    All the comments by the ‘experts’, I feel are valid points; I aint gonna argue, but I feel that Dustins style of coding is very intuitive and clear to understand. Script shortcuts are not something that I was taught at university, obviously they expected students to be a lot more verbose in their coding. Since embarking on my chosen career I have changed my style of coding drastically and taken on board many different styles and ideas that I have discovered in various books, forums and blogs.

    People like dustin that do write blogs and cite examples are helping to shape the next generation of scripters and open them up to new possibilities and giving them confidence in their code.

    What I am trying to say is that Dustin is helping, he is helping a lot, so go easy on him, and to Dustin; thank you for this post and all the others.

    PS: Dustin, whats with the lack of podcasts/screencasts lately? I eagerly await their return.

  38. Dustin Diaz

    @H5 and Ray,
    I’d like to say I paid you to write your comments. Thanks for your kind words. And of course, nice to meet the both of you.

    And Ray, I will most definitely try my best to get the ‘ol mic back up and working. I’d like to get a little more serious with the podcasts and screencasts again. I learned a lot about the way people learn just by doing them. The screencasts especially reveal that people like to see code visually written and explained. There’s nothing like having someone right there explaining it to you.

  39. Ray

    RE: the screencasts.

    dont know about anyone else but I had a bit of trouble with one or two of the screencasts, any chance of NOT encoding them using ‘proprietry’ fruit based video encoding, lol.

  40. H5N1

    No, I don’t think my words were kind, it’s what I think! :)
    I follow you from your very first site version but I had a different nick (here in Italy is complicated to use your real name, you can guess… problems on my job place…) and this post remind me the Top 10 custom JavaScript functions of all time.
    I really understand your position even if I’m a fun of “unobtrusive javascript” and semantic-separate-from-style developing.

  41. Mejores maneras de escribir nuestro Javascript | aNieto2K

    [...] Dustin Diaz, uno de los verdaderos gurus del Javascript mundial, nos deleíta con este post con buenas prácticas para el desarrollo en Javascript. Un post enfocado para los que comienzan a desarrollar conociendo la potencia del lenguaje y de las [...]

  42. Adam

    I fully agree with your little rant on document.getElementById. It certainly needs to be placed into a variable at the very least, not sure about a function though. Like:

    pObject = document.getElementById();

    Although with Prototype it’s just so simple to do:

    $(’myId’);

    Adam @ http://www.talkphp.com/

  43. Andy Davies

    Dan Webb’s addEvent is one of the neatest I’ve seen so far:

    http://www.danwebb.net/2007/11/22/media-ajax

    See slide #75

  44. minghong

    Don’t see how it is really better, e.g. creating an alias to document.getElementById is not necessary.

  45. Shani elharrar

    Dustin, good article, except one thing.

    Ajax is Asynchronous JavaScript and XML - By using responseText you cancel the XML thing,
    So you should output XML from the server-side and use responseXML on the client side.

    This, is how Ajax works :)

  46. Fatih HayrioÄŸlu’nun not defteri

    [...] İyi bir javascript kod yazarı olmak isteyenlere ipuçları Bağlantı [...]

  47. peterr

    Simply wrapping document.getElementById as you have adds nothing but another level of indirection without any benefit but code bloat. If you had added items to evaluate the result or to correct some buggy behavior then it would make sense to do this, as you then be making a subroutine call. Your example is nothing then the equivalent defining let:

    function let( a, b ) {
    return a = b;
    }

    The only difference is amount of typing involved when invoking multiple instances of let(a, b) vs. just using a=b. and the call overhead.

  48. H5N1

    Anyway, the best useful and practical function to me is addLoadEvent by Simon Willison :)
    Why didn’t you put it here and put the addEvent one, Dustin!? :)
    Symply I prefer it!

  49. taylan

    Thank u for this document. I m beginner for javascript and these are very good.

  50. HeavyWeightGeek

    Dude your getting some rough beef for saying it’s for beginners. I’d like to say you article is still very valid (even if some is debatable) and keep up the good work.

  51. Better Tips & Ways To Writing JavaScript | David Bisset: Web Designer, Coder, Wordpress Guru

    [...] Better ways to writing JavaScript, written for beginners (don’t use document.getElementById…), but worthy of bookmarking. Tags: Javascript [...]

  52. Saif Khan

    The main man, I ordered the book! Dude YUI and propotype has been really workin out so far. I am strictly an MS guy (all asp.net thing), one of my objectives now is to get these libs like YUI, mootools, prototype etc to really work in asp.net as I’ve have been having some issues with the MS Ajax (limitations).

    Excellent work, excellent work.

  53. Births 11/26/2007 (Mankato Free Press) | Integral Exp

    [...] more? How about some Basecamp tricks from Adaptive Path? Or perhaps you’d prefer to learn better ways to write JavaScript from Digital Web contributor, Dustin Diaz? It’s a surprise we ever get any work done with all [...]

  54. Ryan

    Hey Dustin, this was a good refresher. I’m a long time reader of the tips on this site (especially YUI stuff) so it was cool running into you at the bar last night at Google Xmas party. I’m eagerly awaiting your book.

  55. Sunday Weekly Roundup #17 - 12/09/2007 » Blog at veanndesign.com

    [...] Better ways to writing JavaScript by Dustin Diaz [...]

  56. The Cave » Blog Archive » Javascript No No’s

    [...] Better ways to writing Javascript. Targeted for beginners, but good stuff. [...]

  57. Keeping you busy through December | Pod Nation

    [...] more? How about some Basecamp tricks from Adaptive Path? Or perhaps you’d prefer to learn better ways to write JavaScript from Digital Web contributor, Dustin Diaz? It’s a surprise we ever get any work done with all [...]

  58. A Plot against Britain? (Middle East Online) | Hidden In Plain View

    [...] more? How about some Basecamp tricks from Adaptive Path? Or perhaps you’d prefer to learn better ways to write JavaScript from Digital Web contributor, Dustin Diaz? It’s a surprise we ever get any work done with all [...]

  59. Alex Mailer

    great article. perfect for the beginners

  60. tetrix

    function get(el) {
    return document.getElementById(el);
    }

    i like this but wouldnt it be better like this?

    function get(el_id) {
    return document.getElementById(el_id);
    }

    google xmas?? ewwww

  61. Alex

    I myself am trying to learn some better JavaScript and this is hopefully going to help me out, thanks for the post.

  62. Diego Perini

    There may be a need to wrap whatever method have a base reference that is going to change.

    In a multi-frame/multi-window environment there are many documents one would want to get elements from, so this will fit with what you say,
    you will have to pass the document and the id to that function.

    A bit stretched Dustin, but I hope it helps… :-)

    Good New Year !!!

  63. Ed Hardy

    Why do i have to be such a sucker for Javascript…

  64. Surf Raporu, 12 Mart 2008 | Taylan Aktepe

    [...] JavaScript için güzel bir başlangıç olabilir. Yazıya gözatmak için tıklayınız. [...]

  65. Links for the Weekend, 4-26-2008

    [...] Better Ways to Writing JavaScript - Good advice by Dustin Diaz… [...]

Get "JavaScript Design Patterns"

"As a web developer, you'll already know that JavaScript™ is a powerful language, allowing you to add an impressive array of dynamic functionality to otherwise static web sites. But there is more power waiting to be unlocked--JavaScript is capable of full object-oriented capabilities, and by applying OOP principles, best practices, and design patterns to your code, you can make it more powerful, more efficient, and easier to work with alone or as part of a team."

Buy JS Design Patterns from Amazon.com Buy JS Design Patterns from Apress

Submit a Prototype

All content copyright © 2003 - 2007 under the Creative Commons License. Wanna know something? Just ask.

About | Archives | Blog Search

[x] close

Loading...

Submit a prototype

By checking this prototype I agree that I am not submitting false credentials, pornography, or a hate crime website. I also understand that by submitting my entry I may or may not be accepted, and if accepted, my entry may be taken down at any given time if I violate these terms.