onclick
Runs code when an element is clicked.
Learn onclick, onchange, onsubmit, oninput as part of the HTML attribute system: what they configure, where they belong and which mistakes to avoid.
Events
HTML supports attributes such as onclick, onchange and onsubmit. They run JavaScript when events happen. They are easy to understand in tiny demos, but they mix structure and behavior.
In real projects, keep HTML as structure and attach behavior from JavaScript with addEventListener. That keeps code easier to maintain, test and secure.
onclick, onchange, onsubmit, oninput. Inline event attributes and why production code usually prefers JavaScript listeners. What belongs here
onclickRuns code when an element is clicked.
onchangeRuns code when a form value changes.
oninputRuns code while an input changes.
onsubmitRuns code when a form submits.
addEventListenerThe JavaScript-first alternative used in production code.
data-actionA clean HTML hook that JavaScript can read.
Syntax in context
They are useful to recognize, but production code is usually cleaner when behavior is attached from JavaScript.
<button type="button" data-action="save">
Save
</button>
<script>
document.querySelector("[data-action=save]").addEventListener("click", saveLesson);
</script>
Good versus weak
<button type="button" data-action="save">
Save
</button>
<script>
document.querySelector("[data-action=save]").addEventListener("click", saveLesson);
</script>
<button onclick="saveLesson(); alert('saved')">
Save
</button>
Rules that matter
You will see them in old code and simple examples.
It separates behavior from markup and scales better.
data-action can describe intent without tying HTML to a function name.
They are harder to lint, test and secure.
Production thinking
Attributes are small, but they change how an element works. A good attribute can make a link usable, an image understandable, a form easier to complete or a script safer to load.
Event behavior must work with keyboard interaction too. Native buttons and form events make this easier.
Moving behavior to JavaScript files improves maintainability and makes CSP security policies easier to use.
Live code lab
Edit the HTML or CSS, then use Run to refresh the preview. The preview is isolated, so links and forms stay inside this practice area.
Mini assignment
Practice assignment
Try it yourself
Self-check
Do not only read this page. Answer these questions out loud or write the answers in your own notes. If one answer feels vague, revisit the examples before moving on.