Nearby lessons
9 of 14JavaScript HTML DOM Events
π What are DOM Events?
JavaScript DOM events let you execute code when users interact with your webpage. Events can be assigned using HTML attributes or JavaScript. Common events include click, input, mouseover, focus, and more.
π HTML Event Attributes
You can directly assign events using HTML attributes such as onclick, onmouseover, etc.
Code Example
π Assign Events Using JavaScript DOM
Instead of using HTML attributes, you can assign events with JavaScript using element.addEventListener() or element.event = function.
Code Example
π onload and onunload Events
onload runs when the page or element finishes loading. onunload runs when the user leaves the page.
Code Example
β¨οΈ oninput Event
Triggered every time a user types or changes input in a field.
Code Example
π onchange Event
Fires when the input loses focus and its value has changed (for input, select, textarea).
Code Example
π±οΈ onmouseover and onmouseout Events
onmouseover triggers when the mouse enters the element, onmouseout when it leaves.
Code Example
π±οΈ onmousedown, onmouseup, and onclick
Use onmousedown when the mouse button is pressed, onmouseup when released, and onclick for a full click action.
Code Example
π‘ onfocus Event
The onfocus event runs when an element (like input) gains focus.