0

My JavaScript code is:

var headline = document.getElementById("mainHeading");
headline.onClick = function() {
    headline.innerHTML = "You clicked the headline.";
};

But nothing happens when I click the headline. It just works when I use onclick instead of onClick (without capital letter C).

The thing is when I debug with both Chrome DevTools and Firebug, they don't show onClick as a syntax error.

Could anyone tell me how to debug it?

Sebastian Zartner
  • 18,808
  • 10
  • 90
  • 132
Tuan van Duong
  • 185
  • 4
  • 14
  • 1
    *"Could anyone tell me how to debug it?"* Sadly, using wrong property names is not that easy to debug. However, the very fact the the function does not get called already tells you that you didn't bind the event handler correctly. Then you should have a look at how you bind the event handler, and then you'd notice that you used `onClick` instead of `onclick`. Not everything can be debugged, some things you have to actually *learn*. https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers – Felix Kling Aug 02 '14 at 17:17

2 Answers2

2

They won't show onClick as syntax error, because it's not.

What you're doing is setting a variable named onClick on the object headline as a function. Everything is fine with that. No error here.

It won't be called though, because the 'browser' will call onclick when a click occured.

And if you don't call onClick yourself, it will never be.

Use onclick.

Yoann
  • 3,020
  • 1
  • 24
  • 34
2

The event is onclick (all lowercase). JavaScript is case sensitive so you must match the casing. When you set onClick you are setting a custom property on your element to the function you specified. The element stores the value, but nothing is ever accessing that property. It's a feature of JavaScript that you can set arbitrary properties on any object so there's nothing in the debuggers that will let you catch this unfortunately.

nkron
  • 19,086
  • 3
  • 39
  • 27
  • As it's not a syntax error to set `onClick`, you can just catch this error by checking whether the code is executed or not, i.e. either visibly or via setting a breakpoint at the `headline.innerHTML ...` line and clicking the `#mainHeading` element and seeing that the breakpoint is not hit. – Sebastian Zartner Aug 04 '14 at 09:49