Most JavaScript-applications perform actions as a response to events. An event is a signal (notification) from the browser that something has happened.
JavaScript lets you react to the event. To react to an event you listen for it and supply a function which will be called by the browser when the event occurs.
Event Categories
There are many types of events. Some of them are:
- Window events: load, unload, scroll, resize ...
- Mouse events: click, dbclick, mouseover, mousedown, mouseenter, mouseleave, mouseup, mouseout ...
- Keyboard events: keydown, keyup, ...
- Object events
- Form events: focus, change, input ...
- Touch events: touchstart, touchmove, ... ...
- More ...
See more in W3schools Events and MDN Events.
In addition, custom events can be defined and handled. For more information see Creating and triggering events, CustomEvent.
For keyboard pressed key codes look at Javascript Char Codes (Key Codes).
Assigning event handlers
For a script to react on the event, there should be a function assigned to it. Functions which react on events are called event handlers (callback). They are usually named like "on+eventtype", for instance: onclick.
Handlers are executed sequentially. That means, if two events happen simultanteously, for example mouseover (mouse has come over an element) and mousemove (mouse moved over an element), their handlers will be executed one after another.
JavaScript event handlers can be divided into two parts: interactive (user dependent) and non-interactive (browser dependent). For example, mouse event is an interactive because it depends on the users action with the mouse. On the other hand page loading event is non-interactive, because this event handler will automatically execute JavaScript code without the user's interactivity.
There are 3 ways of assigning event handlers: markup attribute, onevent DOM property, and special methods.
Handlers by Markup Attribute
A handler can be set directly in the HTML markup, right into the attribute named onevent. This is a simple way for simple tasks. Not recommended because of JavaSctipt code and HTML markup mixing.
Example:
<div onclick="alert( "Thank You" );">Click me please</div>
We can call a function for the event handling instead of writing the code in the markup.
Example:
<script>function fun1() { alert( "Thank You" ); }</script>
<div onclick="fun1();">Click me please</div>
Try it:
We can get the element by usual way to get its properties or modify the element.
Example:
<script>function fun2() { document.getElementById( 'my-div1' ).innerHTML = "Thanks"; }</script>
<div id="my-div1" onclick="fun2();">Click me please</div>
Try it:
Inside an event handler, this references the current element. It can be used to get properties on modify the element.
Example:
<script>function fun3( element ) { element.innerHTML = "Thanks"; }</script>
<div onclick="fun3( this );">Click me please</div>
Try it:
Handlers by DOM-object property
We can use event property to assign an event in the following way:
Example:
<div id="my-div2">Click me please </div>
<script>
//document.getElementById( 'my-div2' ).onclick = fun4;
function fun4() {
alert( "Thanks" );
}
// other way - will replace the previous handler (only one is allowed in this way)
document.getElementById( 'my-div2' ).onclick = function() {
fun4();
};
</script>
Try it:
Example:
<script>
document.querySelector( 'body' ).onresize = resizeFun;
function resizeFun() {
alert( "You have changed the size of the browser window!" );
}
</script>
Try it by resizing the window.
Please, note that the function should be assigned, namely resizeFun, not resizeFun().
Try to resize the browser window.
Assiging handlers using a property is a very simple and popular way. The problem is that only one handler for a certain event type and an element can be set.
Event Listeners
Event listeners is one of the modern ways to handle events. You will use it if you write an application for the modern browsers. Not all old browsers (IE9 and below have different syntax) support it (there is another way to support in old browsers or use JQuery).
We attach a listener to an event and specify the appropriate handler. The main advantage of using event listener: we can use multiple handlers for the same event on the same element; we can remove the handler.
Assigning a handler:
element.addEventListener( event, handler, phase ) For example: elem.addEventListener( "click" , handler, false)
Phase is optional and is used to define event propagation direction in nested elements (from child to parent or from parent to child) if the same event is attached to the child and the parent(s).
The propagation can be stopped by stopPropagation function on event.
It is better to set it always. Usually it is false.
Note that handler gets as input an event. The event has a field called target which defines the element of the event.
Example:
var btn = document.querySelector( '.click-me' );
btn.addEventListener( 'click', function ( event ) {
console.log( event ); // the event details
console.log( event.target ); // the clicked element
}, false);
Removing a handler (phase must be the same as in adding listener):
element.removeEventListener( event, handler, phase ) For example: elem.removeEventListener( 'click', handler, false )
Please, note that the event name goes without the "on" prefix.
See more in W3schools Events and MDN Events.
Event Listener to Multiple Elements
You can attach the same listener to multiple elements by looping on elements. You can also use event delegation. See examples later in this lesson. See also in Listener for multiple elements.