Difference between onclick and onClick

I was going through the Chore Door project and I learned it is possible to call the onclick function directly on the value of an id attribute. (Can be seen around 7:00 of Javascript Interactive Website Chore Door )

For instance the example below shows onclick being called directly on door1.

index.html

    <img id="door1" class="door-frame" src="https://content.codecademy.com/projects/chore-door/images/closed_door.svg">

script.js

const botDoorPath = "https://content.codecademy.com/projects/chore-door/images/robot.svg";
let doorImage1 = document.getElementById("door1");

door1.onclick = () => {
  doorImage1.src = botDoorPath;
}

I have never seen this and started looking up the difference between onclick and onClick. Based on my research, I started assuming onclick is a function in to be called in JS and onClick is just a reference to a function in HTML.

But then I saw onclick being called on a DOM object instead of on the id attribute value in the MDN site: GlobalEventHandlers.onclick - Web APIs | MDN .

What exactly is the difference? Is there a difference or can it be used flexibly and the capitalization is only there because HTML is not case sensitive but JS is case sensitive?

In JavaScript, onclick is one of many `onevent’ properties which can be used to assign event listeners. (More info: Event handling (overview) - Event reference | MDN)

JS is case sensitive, so onClick will not work.

Similarly, there is an HTML attribute onclick which can be used to trigger a JS function like this:

<button onclick=“myFunction()”></button>

HTML5 is not case sensitive, so if you want to spell it onClick or even ONCLICK it will work as expected. However, the current fashion/best practice is to style all tags and attributes in lowercase letters, so onclick is probably the best choice here too. (More info: javascript - onclick or onClick? - Stack Overflow)

2 Likes