Reliable and Recognized JavaScript Certification Online #

Event is simply an action performed by user or browser itself. Whenever something happens to the HTML document or its element, the web browser generates an event. For example loading document, mouse click, key press and element focus web browser turns into events. It is possible to write a JavaScript code that will be invoked when a specific event occurs.

 

Event Handlers

Event handler, called also event listener, is a function that handles an event. Such a function should be registered for specific event type on specific DOM element. Whenever that even occurs, corresponding handler is called.

Registering event handlers

There are several ways to register event handlers. First of all, directly in HTML code you can set the attribute with the name of the event type on the HTML element, that is the event target. Attribute name consists of the word “on” followed by the event name (eg. onclick, onchange, onsubmit). Attribute value should be JavaScript code surrounded by quotes. That code becomes the body of the event handler function.

<button type="button" onclick="alert(new Date());">Show current date</button>

Some types of events like onload refer to the entire document, then you should put the attribute in the body element.

Second, in JavaScript code you can set the property with the name of the event type of the window, document or document element, that is the event target. Property name, consists of the word “on” followed by the event name and should be written in lowercase. Property value should be a valid JavaScript function.

<button type="button" id="myButton">Show current date</button>
var myButton = document.getElementById("myButton");
myButton.onclick = function () {
    alert(new Date());
};

Finally you can use a standard method addEventListener(). This method you should call on the document element, document or window itself, that is the event target. The addEventListener() accepts as the first argument event type, that is the name of the event without the “on” prefix. The second attribute is the function that should be called. The third attribute can be either the use capture boolean flag, default set to false or an options object.

var myButton = document.getElementById("myButton");
var myFunc = function () {
    alert(new Date());
};
myButton.addEventListener('click', myFunc, false);

Using addEventListener() method does not overwrite the onclick property. Instead another event handler is created. The addEventListener() allows you to add multiple event handlers for the same element and type of event. When an event occurs on an element all related event handlers are invoked in the same order in which they were registered.

It is possible to remove event handler registered by the addEventListener() on an element by using opposite method removeEventListener(). It accepts the same three arguments and removes specified event handler.

myButton.removeEventListener('click', myFunc, false);

Calling Event Handlers

An event handler is called whenever an event of specified type occurs on specified element.

Event object

Event handler is called with an Event object passed as an argument. The event object provides information about the event. For example it contains information about event type, event target and information specific for event type like pressed key.

<button type="button" id="myButton">Click here</button>
function eventHandler(event) {
    console.log(event.type);
    console.log(event.target);
}

document.getElementById("myButton").onclick = eventHandler;
// Output:
// "click"        
// "<button id="myButton" type="button">"

When an event handler is registered as HTML element attribute, the event object is available as a event variable.

<input type="button" onclick="alert(event.type)" value="Show event">

Event handler context

When a new event handler is registered for an object, there is set a object property and a new method is defined for this object. That is why inside of an event handler you can use keyword this, that refers to the event target.

<select id="colours">
    <option value="red">red</option>
    <option value="yellow">yellow</option>
    <option value="blue">blue</option>
</select>
<div id="displayColour"></div>
var colours = document.getElementById('colours');
colours.onchange = function() {
    document.getElementById('displayColour').innerHTML = '<span style="color: ' + this.value + '">' + this.value + '</span>';
};

 

Event propagation

Calling order

An document element may have more than one event handler registered for a given event type. All these events are called in a specific order. First it is called event handler registered by setting an object property or HTML element attribute. Then are called event handlers registered by addEventListener() method in the same order in which they were registered.

Event bubbling

Most of events are propagated from the most specific element towards the least specific node in the DOM tree. This feature is also called event bubbling. Consider the following example:

<!DOCTYPE html>
<html>
    <head>
        <title>Event Propagation</title>
    </head>
    <body>
        <div><span>Click here</span></div>
    </body>
</html>

When you click the span element, the click event occurs first on the span element, then it propagates in the following order: on the div element, on the body element, on the html element on the document object and and finally on the window object.

Event capturing

There is an alternative event flow called event capturing. In this flow the last specific node receives the event first and the most specific element receives the event at the end. This provides an opportunity to deal with the event before it reaches its target.
Event capturing works only with event handlers registered with addEventListener() method, when the third argument is set to true. This feature is much less use than event bubbling.

Summarizing, there are three phases of event propagation. The first phase that occurs, is the capturing phase. Second phase is calling event handlers on the target object. The last phase is bubbling phase.

 

Event cancellation

If an event handler is registered by setting an HTML element attribute or an object property the return value affects the propagation of the event. If the return value is false, then the browser’s default action associated with an event is not performed.

<a href="http://example.com" onclick="alert('Inactive link'); return false;">Link</a>

For all events, the browser’s default action for an event can be canceled using preventDefault() method of the event object.

<a href="http://example.com" id="myLink">Link</a>
document.getElementById('myLink').addEventListener('click', function(event) {
    event.preventDefault();
    alert('This link is not active now');
}, false);

The event object has defaultPrevented property, that is set to true if the preventDefault() method is called.

It is also possible to cancel an event propagation. You should use the stopPropagation() method on the event object to prevent propagation of the event to any other object. Only other auction handlers registered on the same object will still be called.

 

Event Types

There are many events and their number is still growing. Some of them are known from the early days of web browsers. New once are defined by the DOM specification led by W3C, by HTML5 APIs and by the solutions for mobile devices.

Form events

The submit event is fired by the form element, when the form is submitted.
The reset event is fired, when the form is reseted.
The click event is fired by buttons, radio buttons and checkboxes, when the user clicks them.
The change event is fired when the form element changes its state. It happens when an element is selected, a box is checked or the user has entered text into text input field and took off the focus.
The focus is fired when an element gains the focus.
The blur is fired when an element lose the focus.

Load events

The load event is fired on the Window object when the document and all its external resources are fully loaded. In this state, the document is ready to be manipulated. Individual document elements like img trigger also this event.
The DomContentLoaded event is fired when the document is loaded and parsed and deferred scripts executed. External resources like images and asynchronous scripts may still be loaded, however the document is ready to be manipulated.
The unload event is fired when the document is being unloaded. It gives you the opportunity to save the user’s data but cannot be used to cancel the unload.
The beforeunload event is similar to the unload event and is fired when the document is about to be unloaded. At this stage, the document is still visible and cancellation is still possible. Depending on the browser, if the returnValue event property has set a string, or a handler function returns a string, this string is displayed in a dialog asking the user for confirmation.

Window events

Window events are mentioned above the load events.
The focus and blur events may also be used as Window events.
The scroll event is fired when the user scrolls the browser window.
The resize event is fired when the user resizes the browser window.

Mouse events

Mouse events are triggered when the user moves or clicks mouse over the HTML document. The event is triggered first on the most deeply nested element, where the mouse pointer is located and it bubbles up through the document.
The event object has several useful properties. The clientX and the clientY properties specify the position of the mouse. The button property specifies which button mouse was clicked. The detail property specifies whether that was single or double click.

The list of mouse events is as follow:
The mousedown is fired when the user presses a mouse button.
The mouseup is fired when the user releases a mouse button.
The click event is fired when the user press and releases a mouse button.
The dblclick is fired when user double-clicks a mouse button.
The mouseover is fired when the mouse pointer is moved onto an element.
The mouseout is fired when the mouse pointer leaves an element.
The mousemove event fires when the user moves the mouse.

Mousewheel events

The wheel event is fired when the user rotates the mouse wheel. The default action of the wheel event depends on the browser. It can be scrolling or zooming.
The wheel event object has deltaX, deltaY and deltaZ properties, which specify rotation in three dimensions.

Keyboard events

Keyboard events are generated when document element or the document itself has focus and the user presses or releases key on the keyboard. Keyboard events bubble up from the most specific element to the document and window.

The keydown event fires when a key is pressed.
The keyup event fires when a key is released.
The keypress event fires after the keydown and before the keyup.

Keyboard events objects have properties that provide details of which key has been pressed or released:
The key property value is a string containing character corresponding to key that was used or standard key value, if the key doesn’t have a printable representation.
The keyCode is a legacy property specifying numerical code identifying the key.
The altKey, ctrKey, shiftKey are properties of key events objects, that describe the state of modifier keys.

No Comments

Reply