JavaScript Coding Standards

Pure JavaScript

After becoming very familiar with how to write JavaScript code using the jQuery framework, I started working on a few mobile projects. On mobile devices jQuery is both a little bloated and sometimes incompatible. But, having grown use to it's syntax and it's ability to separate source and ui code, I wanted to find and set some similar standards for coding in pure JavaScript. What I found is that jQuery made me a lazy JavaScript programmer in many ways.

Get a Pointer to an Element

To grab an element to manipulate (by it's ID) you

myVar = document.getElementById('idName');

I generally prefer to do this outside of functions so that I can do it once and access it from within all my different functions (a global variable).

There are other ways to target the element you're after but I can almost always assign ID's to elements in order to easily target them. When you're writing code for bookmarklets or similar scripts that run on sites you don't have control over, you'll want to look into those.

Dynamically Setting onClick Events

To set an onclick you can either

elementVar.onclick = function() { doFoo(); }

or

elementVar.onclick = doFoo;

but not

elementVar.onclick = doFoo();

The last one executes the doFoo function right away and sets the onClick event to the result returned by that function. Instead, you want to execute the doFoo function when the onclick event happens.

The first way is my preference because it allows more than one function to be executed onClick such as

elementVar.onclick = function() { doFoo(); doBar(); }

It also forces you to think about how you'll be passing the elementVar to those functions. To pass the elementVar itself you would use the this keyword.

elementVar.onclick = function() { doFoo(this); doBar(this); }

References

comments powered by Disqus
javascript_coding_standards.txt · Last modified: 2020/06/01 22:53 (external edit)