Show List
JavaScript Events
Events are change of state that happens on HTML elements. Event handling in JavaScript allows you to respond to events such as user actions (such as clicks, hover, etc.), browser events (such as load or unload), or other events that occur in the browser or on a web page.
You can use event handlers in JavaScript to specify what should happen when an event occurs. For example, you can attach a click event handler to a button element to specify what should happen when the user clicks the button.
JavaScript functions can be called when those events happen. Below are some common events:
- onchange: Triggered when an element changes
- onclick: Triggered on a mouse click
- ondblclick: Triggered on a mouse double-click
- onerror: Triggered when an error occur
- oninput: Triggered when an element gets user input
- oninvalid: Triggered when an element is invalid
- onkeydown: Triggered when a key is pressed
- onkeypress: Triggered when a key is pressed and released
- onkeyup: Triggered when a key is released
- onload: Triggered when the document loads
- onmousedown: Triggered when a mouse button is pressed
- onmousemove: Triggered when the mouse pointer moves
- onmouseout: Triggered when the mouse pointer moves out of an element
- onmouseover: Triggered when the mouse pointer moves over an element
- onmouseup: Triggered when a mouse button is released
- onmousewheel: Triggered when the mouse wheel is being rotated
Here is a sample code where JavaScript function is triggered when value of a text field is changed:
<!DOCTYPE html><html><head><script>function addNumbers() {document.getElementById("err").innerHTML = "";document.getElementById("result").innerHTML = "";var a = document.getElementById("fnum").value;var b = document.getElementById("snum").value;var sum = parseInt(a) + parseInt(b);if (isNaN(sum)) {document.getElementById("err").innerHTML = "Invalid Input";return;}document.getElementById("result").innerHTML = sum;}</script></head><body><h2>Demo - Add Two Numbers</h2><label for="fnum">First Number:</label><br><input type="text" id="fnum"><br><label for="snum">Second Number:</label><br><input type="text" id="snum" onchange="addNumbers()"><br><br><p id="err"></p><p id="result"></p></body></html>
Leave a Comment