View video tutorial

HTML Events

HTML

HTML events trigger an action and acts as an interface between browsers and user.

HTML Event Atrributes


➔ Events trigger actions, and the user performs actions using events.

➔ Each event has a corresponding event handler and is responsible for calling the function.

➔ When the event fires, the event handler calls user-defined functions or built-in functions.

➔ Events can be categorized as Windows Event, Form Event, Keyboard Event, Mouse Event, Clipboard Event, Media Event.

How Events are Handled:


➔ Events are occurrences and actions that occur in the browser due to user interaction with the user interface.

➔ If the events that occur in the browser are not handled, the web page remains static or non-dynamic.

➔ So to make a web page dynamic, the events that occur in the browser must be handled using JavaScript code.

➔ Web developers create JavaScript functions, these functions are called when an event occurs. This process of calling a function against an event is called event handling and the function is called an event handler.

The handler function can be called mainly in two ways:


Inline calling of event handler within HTML code: In this method the JavaScript event handler function is called directly from the HTML code for a specific event. This is not a good approach for event handling because here we cannot follow the important software engineering principle 'separation of concerns'.

Using the addEventListener() method from JavaScript code: In this method, the addEventListener() method is used to specify the event and the handler function responsible for handling the event.

This is the recommended and modern approach to event management.

It helps to manage multiple handlers for multiple events and it provides better control for maintaining the code.

And it clearly separates the concerns of the view and the logic.

Event handling using inline calling of event handler within HTML code:

Example

<!DOCTYPE html>
<html>
<head>
        <title>HTML event handling example</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta content='charset=utf-8' />
        <style>
                .mydiv {
                        border: 1px solid black;
                        padding: 50px 30px;
                        background: rgb(100, 100, 100, 0.3);
                }
        </style>
</head>
<body>
        <h3>HTML event handling example</h3>
        <div class="mydiv">
                Click on the button to change the div properties.
                <button onclick="myHandler()">Click</button>
        </div>
        <script>
                let div = document.querySelector('.mydiv');
                function myHandler() {
                        div.style.border = "3px solid red";
                        div.style.backgroundColor = "#10809050";
                }
        </script>
</body>
</html>
Try it Now »

Copy the code and click on the "Try it Now" button to see how it works.


Event handling using the addEventListener() method from JavaScript code

Example

<!DOCTYPE html>
<html>
<head>
        <title>HTML event handling example</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta content='charset=utf-8' />
        <style>
                .mydiv {
                        border: 1px solid black;
                        padding: 50px 30px;
                        background: rgb(100, 100, 100, 0.3);
                }
        </style>
</head>
<body>
        <h3>HTML event handling example</h3>
        <div class="mydiv">
                Click on the button to change the div properties.
                <button class="btn">Click</button>
        </div>
        <script>
                let div = document.querySelector('.mydiv');
                let btn = document.querySelector('.btn');
                btn.addEventListener('click', myHandler);
                function myHandler() {
                        div.style.border = "3px solid red";
                        div.style.backgroundColor = "#10809050";
                }
        </script>
</body>
</html>
Try it Now »

Copy the code and click on the "Try it Now" button to see how it works.


Event handling using the addEventListener() method from JavaScript code (alternate syntax)

Example

<!DOCTYPE html>
<html>
<head>
        <title>HTML event handling example</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta content='charset=utf-8' />
        <style>
                .mydiv {
                        border: 1px solid black;
                        padding: 50px 30px;
                        background: rgb(100, 100, 100, 0.3);
                }
        </style>
</head>
<body>
        <h3>HTML event handling example</h3>
        <div class="mydiv">
                Click on the button to change the div properties.
                <button class="btn">Click</button>
        </div>
        <script>
                let div = document.querySelector('.mydiv');
                let btn = document.querySelector('.btn');
                btn.addEventListener('click', (event) => {
                        div.style.border = "3px solid red";
                        div.style.backgroundColor = "#108090";
                });
        </script>
</body>
</html>
Try it Now »

Copy the code and click on the "Try it Now" button to see how it works.


The click Event

<button type="button" onclick="handlerFunction()">Click Here!</button>

Example

<!DOCTYPE html>
<html>
<head>
    <title>Event Example</title>
</head>
<body>
    <h1>Event Example</h1>
    <button type="button" onclick="handlerFunction()">Click Here!</button>
    <script>
        function handlerFunction() {
            alert("Hello from JavaScript!");
        }
    </script>
</body>
</html>
Try it Now »

Click on the "See output" button to see how it works.


Windows Events Global Attributes

This section describes attributes that are for the window object (body element)

Event Event Handler Description
afterprint onafterprint Fires after the document is printed
beforeprint onbeforeprint Fires before the document is printed
beforeunload onbeforeunload Fires when the document is about to be unloaded.
error onerror Fires when an error occurs.
hashchange onhashchange Fires when there has been changes to the anchor part of the a URL.
load onload Fires after the page is finished loading.
message onmessage Fires when the message is triggered.
offline onoffline Fires when the browser starts to work offline.
online ononline Fires when the browser starts to work online.
pagehide onpagehide Fires when a user navigates away from a page.
pageshow onpageshow Fires when a user navigates to a page.
popstate onpopstate Fires when the window's history changes.
resize onresize Fires when the browser window is resized.
storage onstorage Fires when a Web Storage area is updated.
unload onunload Fires once a page has unloaded or the window has been closed.

Form Events Global Attributes

This section describes attributes that are common to all HTML elements(mostly form element)

Event Event Handler Description
blur onblur Fires when element loses focus.
change onchange Fires when the value of the element is changed.
contextmenu oncontextmenu Fires when a context menu is triggered.
focus onfocus Fires when the element gets focus.
input oninput Fires when an element gets user input.
invalid oninvalid Fires when an element is invalid.
reset onreset Fires when the forms Reset button is clicked.
search onsearch Fire when the user writes something in the search field.
select onselect Fires when any text has been selected in an element.
submit onsubmit Fires when a form is submitted.

Keyboard Events Global Attributes

This section describes attributes that are common to all input elements(mostly text input)

Event Event Handler Description
keydown onkeydown Fires when a user presses a key and hold.
keypress onkeypress Fires when a user presses a key.
keyup onkeyup Fires when a user releases a key.

Mouse Events Global Attributes

This section describes attributes that are common to all HTML elements.

Event Event Handler Description
click onclick Fires when a mouse click on the element.
dblclick ondblclick Fires when a mouse double-click on the element.
mousedown onmousedown Fires when a mouse button is pressed down on an element.
mousemove onmousemove Fires when the mouse pointer is moving over an element.
mouseout onmouseout Fires when the mouse pointer moves out of an element.
mouseover onmouseover Fires when the mouse pointer moves over an element.
mouseup onmouseup Fires when a mouse button is released over an element.
wheel onwheel Fire when the mouse wheel rolls up or down over an element.

Clipboard Events Global Attributes

This attributes are for the text elements.

Event Event Handler Description
copy oncopy Fires when the user copies the content of an element.
cut oncut Fires when the user cuts the content of an element.
paste onpaste Fires when the user pastes some content in an element.

Media Events Global Attributes

This section describes attributes that are for mostly media objects.

Event Event Handler Description
abort onabort Fires when abort.
canplay oncanplay Fires when a file is ready to start playing.
canplaythrough oncanplaythrough Fires when a file can be played all the way to the end without pausing for buffering.
cuechange oncuechange Fires when the cue changes in a element.
durationchange ondurationchange Fires when the length of the media changes.
emptied onemptied Fires when something happens bad and the file is suddenly unavailable.
ended onended Fire when the media has reached its last stage.
error onerror Fires when an error occurs.
loadeddata onloadeddata Fires when media data is loaded.
loadedmetadata onloadedmetadata Fires when meta data are loaded.
loadstart onloadstart Fires just as the file begins to load before anything is actually loaded.
pause onpause Fires when the media is paused.
play onplay Fires when the media is ready to play.
playing onplaying Fires when the media is playing.
progress onprogress Fires when the browser is in the process of getting the media data.
ratechange onratechange Fires each time the playback rate changes.
seeked onseeked Fires when the seeking attribute is set to false.
seeking onseeking Fires when the seeking attribute is set to true.
stalled onstalled Fires when the browser is unable to fetch the media data.
suspend onsuspend Fires when fetching the media data is stopped.
timeupdate ontimeupdate Fires when the playing position has changed.
volumechange onvolumechange Fires each time the volume is changed.
waiting onwaiting Fires when the media has paused.

Drag & Drop Events

During drag operations, several event types are fired. Each drag event type has an associated event handler:

Event Event Handler Description (Fires)
drag ondrag When a dragged item (element or text selection) is dragged.
dragend ondragend When a drag operation ends (such as releasing a mouse button).
dragenter ondragenter When a dragged item enters a valid drop target.
dragleave ondragleave When a dragged item leaves a valid drop target.
dragover ondragover When a dragged item is being dragged over a valid drop target, every few hundred milliseconds.
dragstart ondragstart When the user starts dragging an item.
drop ondrop When an item is dropped on a valid drop target.

Learning with HTML Editor "Try it Now"

You can edit the HTML code and view the result using online editor.

The keyup Event

<input id="text1" type="text" onkeyup="handlerFunction()" placeholder="Type something here"/>

Example

<!DOCTYPE html>
<html>
<head>
    <title>Event Example</title>
</head>
<body>
    <h1>Event Example</h1>
    <h2 id="p1"></h2>
    <input id="text1" type="text" onkeyup="handlerFunction()" placeholder="Type something here"/>
    <script>
        function handlerFunction() {
            var t1 = document.getElementById("text1").value;
            document.getElementById("p1").innerHTML=t1;
        }
    </script>
</body>
</html>
Try it Now »

Click on the "See output" button to see how it works.