Responding to User Interactions
Events are actions that happen in the browser - like clicking a button, moving the mouse, pressing a key, or submitting a form.
JavaScript can 'listen' for these events and execute code in response, making web pages interactive and responsive to user actions.
There are many types of events for different user interactions and browser behaviors.
// Mouse Events
element.onclick = function() {
console.log('Clicked!');
};
element.ondblclick = function() {
console.log('Double clicked!');
};
element.onmouseover = function() {
console.log('Mouse over!');
};
// Keyboard Events
input.onkeydown = function() {
console.log('Key pressed');
};
input.onkeyup = function() {
console.log('Key released');
};
// Form Events
form.onsubmit = function() {
console.log('Form submitted');
return false; // Prevent actual submission
};
input.onchange = function() {
console.log('Value changed');
};
input.onfocus = function() {
console.log('Input focused');
};
- click - Single mouse click on an element
- dblclick - Double click on an element
- mouseover/mouseout - Mouse enters/leaves element area
- keydown/keyup - Keyboard key pressed/released
- change - Form input value changes
- focus/blur - Element gains/loses focus
- submit - Form is submitted
- load - Page or image finishes loading
Try Different Events
<div class="event-demo">
<button id="clickBtn">Click Me</button>
<button id="hoverBtn">Hover Over Me</button>
<input type="text" id="keyInput" placeholder="Type something...">
<select id="selectBox">
<option>Select option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<div id="output">Events will appear here...</div>
</div>
Note: Inline Events: Avoid using onclick attributes in HTML. Use JavaScript event handlers instead for better separation.
Note: Event Handlers: Only one handler can be assigned using 'on' properties. Use addEventListener for multiple handlers.
Note: Return False: Returning false from event handlers can prevent default browser behavior (like form submission).