0% found this document useful (0 votes)
6 views

Event in Javascript

Uploaded by

tobilobasam300
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Event in Javascript

Uploaded by

tobilobasam300
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Event in JavaScript

What is an event?
Events are things that happen in the system you are programming, which the system tells you about so
your code can react to them. — the system produces (or "fires") a signal of some kind when an event
occurs, and provides a mechanism by which an action can be automatically taken (that is, some code
running) when the event occurs. Events are fired inside the browser window, and tend to be attached to
a specific item that resides in it. This might be a single element, a set of elements, the HTML document
loaded in the current tab, or the entire browser window. There are many different types of events that
can occur.
For example:
• The user selects, clicks, or hovers the cursor over a certain element.
• The user chooses a key on the keyboard.
• The user resizes or closes the browser window.
• A web page finishes loading.
• A form is submitted.
• A video is played, paused, or ends.
• An error occurs.

Events are fired to notify code of "interesting changes" that may affect code execution. These can arise
from user interactions such as using a mouse or resizing a window, changes in the state of the
underlying environment (e.g. low battery or media events from the operating system), and other causes.
Each event is represented by an object that is based on the event interface, and may have additional
custom fields and/or functions to provide information about what happened.

In JavaScript, event handling is a fundamental part of creating interactive web applications. It allows
developers to define code that will be executed when a particular event occurs.

To react to an event, you attach an event handler to it. This is a block of code (usually a JavaScript
function that you as a programmer create) that runs when the event fires. When such a block of code is
defined to run in response to an event, we say we are registering an event handler. Note: Event handlers
are sometimes called event listeners — they are pretty much interchangeable for our purposes, although
strictly speaking, they work together. The listener listens out for the event happening, and the handler is
the code that is run in response to it happening.

Note: Web events are not part of the core JavaScript language — they are defined as part of the APIs
built into the browser.

There are various types of events in JavaScript, such as mouse events (click, hover, etc.), keyboard
events (keypress, keyup, etc.), form events (submit, change, etc.), and many others.

To handle events in JavaScript, you typically:


1. Select the HTML element you want to listen for events on.
2. Attach an event listener to that element, specifying the event type and the function to be
executed when the event occurs.
3. Write the function that will be executed when the event occurs.
For example, let's say you have a button with an id of "myButton" and you want to execute a function
called "handleClick" when it's clicked:
HTML code.

//html code
<button id="myButton">Click Me</button>

JavaScript code.

//Javascript code

// Select the button element


const button = document.getElementById('myButton');

// Attach an event listener to the button


button.addEventListener('click', handleClick);

// Define the function to be executed when the button is clicked


function handleClick() {
console.log('Button clicked!');
// Additional code to be executed when the button is clicked
}

JavaScript Event Handlers


Event handlers can be used to handle and verify user input, user actions, and browser actions:
•Things that should be done every time a page loads
•Things that should be done when the page is closed
•Action that should be performed when a user clicks a button
•Content that should be verified when a user inputs data
•And more ...
Many different methods can be used to let JavaScript work with events:
•HTML event attributes can execute JavaScript code directly
•HTML event attributes can call JavaScript functions
•You can assign your own event handler functions to HTML elements
•You can prevent events from being sent or being handled
•And more ...

Common JavaScript Events Table

onclick Triggered when an element is clicked.

onmouseover Fired when the mouse pointer moves over an element.

onmouseout Occurs when the mouse pointer leaves an element.


onclick Triggered when an element is clicked.

onkeydown Fired when a key is pressed down.

onkeyup Fired when a key is released.

onchange Triggered when the value of an input element changes.

onload Occurs when a page has finished loading.

onsubmit Fired when a form is submitted.

onfocus Occurs when an element gets focus.

onblur Fired when an element loses focus.

Event Bubbling or Event Capturing?


There are two ways of event propagation in the HTML DOM, bubbling and capturing.
Event propagation is a way of defining the element order when an event occurs. If you have a <p>
element inside a <div> element, and the user clicks on the <p> element, which element's "click" event
should be handled first?

In bubbling the inner most element's event is handled first and then the outer: the <p> element's click
event is handled first, then the <div> element's click event.

In capturing the outer most element's event is handled first and then the inner: the <div> element's
click event will be handled first, then the <p> element's click event.

With the addEventListener() method you can specify the propagation type by using the "useCapture"
parameter:
addEventListener(event, function, useCapture);

The default value is false, which will use the bubbling propagation, when the value is set to true, the
event uses the capturing propagation.

Example below:
<!DOCTYPE html>
<html>
<head>
<style>
#myDiv1, #myDiv2 {
background-color: coral;
padding: 50px;
}
#myP1, #myP2 {
background-color: white;
font-size: 20px;
border: 1px solid;
padding: 20px;
}
</style>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
</head>
<body>

<h2>JavaScript addEventListener()</h2>

<div id="myDiv1">
<h2>Bubbling:</h2>
<p id="myP1">Click me!</p>
</div><br>

<div id="myDiv2">
<h2>Capturing:</h2>
<p id="myP2">Click me!</p>
</div>
<script>
document.getElementById("myP1").addEventListener("click", function() {
alert("You clicked the white element!");
}, false);

document.getElementById("myDiv1").addEventListener("click", function() {
alert("You clicked the orange element!");
}, false);

document.getElementById("myP2").addEventListener("click", function() {
alert("You clicked the white element!");
}, true);

document.getElementById("myDiv2").addEventListener("click", function() {
alert("You clicked the orange element!");
}, true);
</script>
HTML DOM Events

Event Occurs When Belongs To


abort The loading of a media is aborted UiEvent, Event
afterprint A page has started printing Event
animationend A CSS animation has completed AnimationEvent
animationiteration A CSS animation is repeated AnimationEvent
animationstart A CSS animation has started AnimationEvent
beforeprint A page is about to be printed Event
beforeunload Before a document is about to be unloaded UiEvent, Event
blur An element loses focus FocusEvent
The browser can start playing a media (has
canplay Event
buffered enough to begin)
The browser can play through a media without
canplaythrough Event
stopping for buffering
change The content of a form element has changed Event
click An element is clicked on MouseEvent
contextmenu An element is right-clicked to open a context menu MouseEvent
copy The content of an element is copied ClipboardEvent
cut The content of an element is cut ClipboardEvent
dblclick An element is double-clicked MouseEvent
drag An element is being dragged DragEvent
dragend Dragging of an element has ended DragEvent
dragenter A dragged element enters the drop target DragEvent
dragleave A dragged element leaves the drop target DragEvent
dragover A dragged element is over the drop target DragEvent
dragstart Dragging of an element has started DragEvent
drop A dragged element is dropped on the target DragEvent
durationchange The duration of a media is changed Event
ended A media has reach the end ("thanks for listening") Event
error An error has occurred while loading a file ProgressEvent, UiEvent, Event
focus An element gets focus FocusEvent
focusin An element is about to get focus FocusEvent
focusout An element is about to lose focus FocusEvent
fullscreenchange An element is displayed in fullscreen mode Event
An element can not be displayed in fullscreen
fullscreenerror Event
mode
There has been changes to the anchor part of a
hashchange HashChangeEvent
URL
input An element gets user input InputEvent, Event
invalid An element is invalid Event
keydown A key is down KeyboardEvent
keypress A key is pressed KeyboardEvent
keyup A key is released KeyboardEvent
load An object has loaded UiEvent, Event
loadeddata Media data is loaded Event
Meta data (like dimensions and duration) are
loadedmetadata Event
loaded
loadstart The browser starts looking for the specified media ProgressEvent
message A message is received through the event source Event
mousedown The mouse button is pressed over an element MouseEvent
mouseenter The pointer is moved onto an element MouseEvent
mouseleave The pointer is moved out of an element MouseEvent
mousemove The pointer is moved over an element MouseEvent
mouseover The pointer is moved onto an element MouseEvent
mouseout The pointer is moved out of an element MouseEvent
mouseup A user releases a mouse button over an element MouseEvent
mousewheel Deprecated. Use the wheel event instead WheelEvent
offline The browser starts working offline Event
online The browser starts working online Event
open A connection with the event source is opened Event
pagehide User navigates away from a webpage PageTransitionEvent
pageshow User navigates to a webpage PageTransitionEvent
paste Some content is pasted in an element ClipboardEvent
pause A media is paused Event
play The media has started or is no longer paused Event
playing The media is playing after being paused or bufferedEvent
popstate The window's history changes PopStateEvent
progress The browser is downloading media data Event
ratechange The playing speed of a media is changed Event
resize The document view is resized UiEvent, Event
reset A form is reset Event
scroll An scrollbar is being scrolled UiEvent, Event
search Something is written in a search field Event
seeked Skipping to a media position is finished Event
seeking Skipping to a media position is started Event
select User selects some text UiEvent, Event
show A <menu> element is shown as a context menu Event
stalled The browser is trying to get unavailable media data Event
storage A Web Storage area is updated StorageEvent
submit A form is submitted Event
suspend The browser is intentionally not getting media data Event
The playing position has changed (the user moves
timeupdate Event
to a different point in the media)
toggle The user opens or closes the <details> element Event
touchcancel The touch is interrupted TouchEvent
touchend A finger is removed from a touch screen TouchEvent
touchmove A finger is dragged across the screen TouchEvent
touchstart A finger is placed on a touch screen TouchEvent
transitionend A CSS transition has completed TransitionEvent
unload A page has unloaded UiEvent, Event
The volume of a media is changed (includes
volumechange Event
muting)
A media is paused but is expected to resume (e.g.
waiting Event
buffering)
wheel The mouse wheel rolls up or down over an element WheelEvent

You might also like