HTML Events
HTML events are actions or occurrences that take place on HTML elements, such as a click, hover, page load, or key press.
JavaScript can be used to respond to these events, enabling interactive behavior.
Below is a list of frequently used HTML events that interact with elements on a webpage:
onchange
: Triggered when an HTML element’s value is modified.onclick
: Activated when a user clicks on an HTML element.onmouseover
: Occurs when the user hovers the mouse pointer over an element.onmouseout
: Fires when the user moves the mouse pointer away from an element.onkeydown
: Activated when a user presses a key on the keyboard.onload
: Happens when the page has fully loaded in the browser.
JavaScript Event Handlers
When an event occurs, JavaScript enables you to run custom code when these events are detected.
In HTML, event handlers can be added to elements with inline JavaScript code through attributes.
You can use either single or double quotes when adding JavaScript to an event handler:
Example: Using single quotes.
<element event='some JavaScript'>
Example: Using double quotes.
<element event="some JavaScript">
Example: The onclick
event can be used with a <button>
to run JavaScript code when the button is clicked.
<button onclick="document.getElementById('demo').textContent = 'Sample text'">Show Text</button>
JavaScript code is often several lines long. It is more common to see event attributes calling functions.
<button onclick="showText()">Show Text</button>
<script>
function showText() {
const Text = "Sample text";
document.getElementById("demo").textContent = Text;
}
</script>
JavaScript addEventListener()
Method
You can also attach event handlers using JavaScript by adding an event listener to an element. This method is preferred as it allows multiple event listeners to be added to the same element.
<button id="myButton">Click Me</button>
<script>
// Select the button element by its ID
const button = document.getElementById("myButton");
// Add an event listener to the button
button.addEventListener("click", function() {
alert("Hello! You clicked the button.");
});
</script>
Explanation:
- We used
addEventListener()
to attach the event handler to the button. - When the button is clicked, the anonymous function is executed, showing the alert.
Event Handlers with Multiple Events
You can add multiple event listeners to the same element, and they can handle different events.
<button id="myButton">Click or Hover Me</button>
<script>
const button = document.getElementById("myButton");
// Click event
button.addEventListener("click", function() {
alert("Button clicked!");
});
// Mouseover event
button.addEventListener("mouseover", function() {
alert("Mouse is over the button!");
});
</script>
Explanation:
- The button has two event listeners: one for a
click
event and another for amouseover
event. - Different actions will occur depending on whether the user clicks the button or hovers over it.