47

I thought that binding the click event in javascript is done by using node.onclick, and Chrome/Firefox seem to agree with me, but I saw it written .onClick here 4 times by 3 people, so it can't be a typo and I doubt that it's a coincidence.

So, why are people writing onClick when it does not work?

UPDATE: There are two good explanations; I don't know which one of them is the most plausible, so I will accept the answer based on popular vote, tomorrow.

Community
  • 1
  • 1
Gabi Purcaru
  • 30,940
  • 9
  • 79
  • 95
  • One more thing to add: if the old XHTML DOCTYPE is used, all attributes must be in lower case. – Raptor Aug 26 '14 at 09:33

4 Answers4

32

Because some browsers (depending on the DOCTYPE) are tolerant of the inline onClick="something();" attribute...it seems to have spread a bit, even into JavaScript questions where it doesn't work, since case matters.

Also, specifically to stackoverflow...people using it in questions...well, most of the time they wouldn't be asking a question if their code worked :)

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
15

@Nick Craver pretty much has it nailed down and has my vote; I just wanted to add my thought.

I think it's onClick is often used in conversation because it's a bit more readable, and as an old habit from those of us who predate all lowercase HTML. However, in code - both JavaScript and HTML, onclick is correct and the only way it should appear. Even if you're using an older HTML doctype, stick to lowercase. If you ever update to a more strict doctype, you'll be glad your code doesn't need to be checked for case.

Surreal Dreams
  • 26,055
  • 3
  • 46
  • 61
12

It's just that for most browsers HTML attributes are case insensitive, but JS is case-sensitive. onClick will work in html, but if you're defining the handler in JS, you need to use the lowercased onclick.

Gopherkhan
  • 4,317
  • 4
  • 32
  • 54
  • in XHTML, HTML attributes are case sensitive. Most browsers will understand and render it fine, but your code will fail validation. – Surreal Dreams Dec 07 '10 at 19:36
  • hmm. Lax browser handling must have been what I was reading. I just read something about this the other week. – Gopherkhan Dec 07 '10 at 22:55
1

In that specific question, I used "onClick" as the original question had it in that vein and I try to change as little of the OPs code as possible to make a solution, so that they can see their mistake easily.

The camel case is invalid technically, though I like camel case in general. Frankly, it always annoys me when I see that method, as I think "Where's jQuery!".

It is heavily prevalent in the world, I see it all the time in source.

I edited my answer on the referenced question to fit, thanks for pointing it out.

Orbling
  • 20,413
  • 3
  • 53
  • 64