Javascript

Home Load Console Selectors CSS Form Strings If Else Array Reg Exp Date & Time setTimeout JSON Loops Objects Animation Fat Arrow Class Import IIFE undefined Tabulator.js ES6 Event Listeners AJAX Hide Elements Create Elements Checkbox ejs
O O

Weather Controls

Time Of Day
Rain
Wind Speed
Wind Direction
Clouds

Javascript : Event Listeners

2023-01-04

7 Ways to Listen for Events:

let button = document.getElementById("myButton");
function handleClick() {}

// 1. Using the addEventListener method with anonymous functions:
button.addEventListener("click", function() {})

// 2. Using the addEventListener method with named functions:
button.addEventListener("click", handleClick);

// 3. Using the on method with anonymous functions:
button.onclick = function () {}

// 4. Using the on method with named functions:
button.onclick = handleClick;

// 5. Using the addEventListener method with event delegation:
document.body.addEventListener("click", function(event) {
    if (event.target.tagName === "BUTTON") {
        //...
    }
})

// 6.  Using the on method with event delegation:
document.body.onclick = function(event) {
    if (event.target.tagName === "BUTTON") {
        //...
    }
}
<!-- 7 Using the on method with inline event handlers: -->
<button onclick="handleClick(this);">click</button>

Some more inline options:

<input type="input" name="dig1" value="" onkeydown="">
<input type="input" name="dig1" value="" onkeyup="">
<input type="input" name="dig1" value="" onkeypress="">
<input type="input" name="dig1" value="" onchange="">
<input type="input" name="dig1" value="" onblur="">
<input type="input" name="dig1" value="" onfocus="">
<input type="input" name="dig1" value="" oninput=""> // runs when element gets user iput