views:

1229

answers:

4

In notepad++, I was writing a javascript file, and something didn't work: an alert had to be shown when a button was clicked, but it wasn't working.

I has used the auto-complete plugin provided with Notepad++, which presented me with "onClick".

When I changed the capital C to a small c, it did work.

So first of all, when looking at the functions in the auto-completion, I noticed a lot of functions using capitals.

But when you change getElementById to getelementbyid, you also get an error...

And to make matters worse, my handbook from school writes all the stuff with capital letters but the solutions are all done in small letters.

So what is it with Javascript and it's selective nature towards which functions can have capital letters in them and which can't?

+17  A: 

Javascript is ALWAYS case-sensitive.

It sounds as thought you are talking about whether html attributes (e.g. onclick) are or are not case-sensitive. The answer is that the attributes are not case sensitive, but the way that we access them through the DOM is. So, you can do this:

<div id='divYo' onClick="alert('yo!');">Say Yo</div> // Upper-case 'C'

or:

<div id='divYo' onclick="alert('yo!');">Say Yo</div> // Lower-case 'C'

but through the DOM you must use the correct case. So this works:

getElementById('divYo').onclick = function() { alert('yo!'); }; // Lower-case 'C'

but you cannot do this:

getElementById('divYo').onClick = function() { alert('yo!'); }; // Upper-case 'C'

EDIT: CMS makes a great point that most DOM methods and properties are in camelCase. The one exception that comes to mind are event handler properties and these are generally accepted to be the wrong way to attach to events anyway.

Prestaul
+1  A: 

JavaScript API methods are almost all called with lowerCamelCase names, and JavaScript is case-sensitive

CMS
+1  A: 

Javascript should always be case sensitive, but I've seen cases in Internet Explorer where it tolerates all upper case for some function names but not others. I think it is limited to functions that also exist in Visual Basic, as there is some odd inbreeding between the interpreters. Clearly this behavior should be avoided, unless of course your intention is to make code that only runs in one browser :)

Jeff
+1  A: 

A few objects is IE aren't always case-sensitive, including some/most/all ActiveX -- why both XHR.onReadyStateChange and XHR.onreadystatechange would work fine in IE5 or IE6, but only the latter would work with the native XMLHttpRequest object in IE7, FF, etc.

But, a quick reference for "standard" API casing:

  • UPPERCASE - Constants (generally symbolic, since const isn't globally supported)
  • Capitalized - Classes/Object functions
  • lowercase - Events
  • camelCase - everything else

No 100% guarantees. But, majority-wise, this is accurate.

Jonathan Lonowski