JavaScript - tutorial - 12 - events

revision:


Content

Events are "things" AnimationEvent Object: events when CSS animation runs ClipboardEvent Object: events when the clipboard is modified DragEvent Object: events when elements are dragged or dropped FocusEvent Object: events when elements get or loose focus Form events HashChangeEvent Object: events when anchor of an URL changed InputEvent Object: events when an input element is changed KeyboardEvent Object: events when a user presses a key on the keyboard MouseEvent Object: events when the mouse interacts with the HTML document PageTransitionEvent Object: events when a user navigates to or from a webpage PopStateEvent Object: events that occur when the window's history changes ProgressEvent Object: events when loading external resources StorageEvent Object: events when there is changes in the window's storage area TouchEvent Object: events when a user touches a touch-based device TransitionEvent Object: events when a CSS transition runs UiEvent Object: events that are triggered from the user interface WheelEvent Object: events when the mouse wheel is scrolling Media events Other events Errors Error name values Frame events Events examples


Events are "things"

top

An HTML event can be something the browser or a user does, such as: an HTML web page has finished loading, an HTML input field was changed, an HTML button was clicked.

JavaScript provides code to be executed when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

Examples: events



code:
                    <div class="spec">
                        <button onclick="document.getElementById('event01').innerHTML=Date()"> The time is?</button><br><br>
                        <a  id="event01"></a>
                    </div>
                

AnimationEvent Object: events when CSS animation runs

top

Animation events are:

animationstart : CSS animation has started.

animationend : CSS animation is complete.

animationiteration : CSS animation is repeated.

Examples: animation event object

Click me to start the animation.
code:
                    <div>
                        <div id="myDIV" onclick="myFunction()">Click me to start the animation.</div>
                    </div>
                    <style>
                        #myDIV {width: 80%; height: 2vw; background: orange;position: relative; font-size: 1.2vw; padding:1.6vw; color:green;}
                        @keyframes mymove {
                            from {top: 0vw;}
                            to {top: 10vw;}
                        }
                    </style>
                    <script>
                        const div1 = document.getElementById("myDIV");
                        function myFunction() {
                            div1.style.animation = "mymove 4s 2";
                        }
                        div1.addEventListener("animationstart", myStartFunction);
                        div1.addEventListener("animationiteration", myRepeatFunction);
                        div1.addEventListener("animationend", myEndFunction);
                        function myStartFunction() {
                            this.innerHTML = "The animation has started";
                            this.style.backgroundColor = "pink";
                        }
                        function myRepeatFunction() {
                            this.innerHTML = "The animation was played again";
                            this.style.backgroundColor = "lightblue";
                        }
                        function myEndFunction() {
                            this.innerHTML = "The animation has completed";
                            this.style.backgroundColor = "lightgray";
                        }
                    </script>
                

AnimationEvent properties:

animationName : the name of the animation; the animationName property is read-only and is the value of the animation-name CSS property.

Syntax : event.animationName

elapsedTime : the nummber of seconds an animation has been running; the elapsedTime property always returns "0" for the animationstart event. Its value is not affected if the animation is paused. The property is read-only.

Syntax : event.elapsedTime

pseudoElement : the name of the pseudo-element of the animation


ClipboardEvent Object: events when the clipboard is modified

top

Clipboard events are:

oncopy : user copies the content of an element.

oncut : the user cuts an element's content.

onpaste : a user pastes content in an element.

Examples: clipboard events

code:
                    <div>
                        <input type="text" oncopy="copyClipboard()" value="try to copy me">
                        <p id="clip1"></p>
                        <input type="text" oncut="cut()" value="Try to cut this text">
                        <p id="clip2"></p>
                        <input type="text" onpaste="paste()" value="Paste something here" size="40">
                        <p id="clip3"></p>
        
                    </div>
                    <script>
                        function copyClipboard() {
                            document.getElementById("clip1").innerHTML = "You copied text!"
                        }
                        function cut() {
                            document.getElementById("clip2").innerHTML = "You cutted text!";
                            }
                        function paste() {
                            document.getElementById("clip3").innerHTML = "You pasted text!";
                        }
                    </script>
                

ClipboardEvent proprties:

clipboardData : an object containing the data affected by the clipboard operation


DragEvent Object: events when elements are dragged or dropped

top

Drag events are:

ondrag : an element is dragged.

ondragend : the user has finished dragging the element.

ondragenter : the dragged element enters a drop target.

ondragleave : a dragged element leaves the drop target.

ondragover : the dragged element is on top of the drop target.

ondragstart : user starts to drag an element.

ondrop : dragged element is dropped on the drop target.

Examples: drag events

Drag the text up and down between the two rectangles:

Drag me!

code:
                    <div>
                        <p>Drag the text up and down between the two rectangles:</p>
                        <div class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)">
                            <p ondragstart="dragStart(event)" ondrag="dragging(event)" draggable="true" id="dragtarget">Drag me!</p>
                        </div>
                        <p id="drag1"></p>
                        <div class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
                    </div>
                    <style>
                        .droptarget {width: 10vw; height: 3.5vw; padding: 1vw; border: 0.1vw solid black;}
                        #dragtarget{color: orangered;}   
                    </style>
                    <script>
                        /* Events fired on the drag target */
                        function dragStart(event) {
                            event.dataTransfer.setData("Text", event.target.id);
                        }
                        function dragging(event) {
                            document.getElementById("drag1").innerHTML = "The text is being dragged";
                        }
                        /* Events fired on the drop target */
                        function allowDrop(event) {
                            event.preventDefault();
                        }
                        function drop(event) {
                            event.preventDefault();
                            const data = event.dataTransfer.getData("Text");
                            event.target.appendChild(document.getElementById(data));
                            document.getElementById("drag1").innerHTML = "The text was dropped";
                        }
                    </script>
                

Drag the text up and down between the two rectangles:

Drag me!

code:
                    <div>
                        <p>Drag the text up and down between the two rectangles:</p>
                        <div class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)">
                            <p ondragstart="dragStart(event)" ondragend="dragEnd(event)" draggable="true" id="dragtarget2">Drag me!</p>
                        </div>
                        <p id="drag2"></p>
                        <div class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
                    </div>
                    <style>
                        .droptarget {width: 10vw; height: 3.5vw; padding: 1vw; border: 0.1vw solid black;}
                        #dragtarget2{color: blue;}   
                    </style>
                    <script>
                        function dragStart(event) {
                            event.dataTransfer.setData("Text", event.target.id);
                            document.getElementById("drag2").innerHTML = "Dragging started";
                        }
                        function dragEnd(event) {
                            document.getElementById("drag2").innerHTML = "Dragging ended.";
                            }
                        function allowDrop(event) {
                            event.preventDefault();
                        }
                        function drop(event) {
                            event.preventDefault();
                            const data = event.dataTransfer.getData("Text");
                            event.target.appendChild(document.getElementById(data));
                            }
                    </script>
                

DragEvent properties

dataTransfer: the data that is dragged or dropped


FocusEvent Object: events when elements get or loose focus

top

Focus events are:

onblur : an element loses focus

onfocus : an element gets focus

onfocusin : an element is about to get focus

onfocusout : an element is about to lose focus

Examples: focus events

onblur

Enter your name:

When you leave the input field, a function is triggered which transforms the input text to upper case.

onfocus

Enter your name:

When the input field gets focus, a function changes the background-color.

onfocusin

Enter your name:

When the input field gets focus, a function changes the background-color.

onfocusout

Enter your name:

When you leave the input field, a function transforms the input text to upper case.

code:
                    <div>
                        <p>onblur</p>
                        Enter your name: <input type="text" id="fname_1a" onblur="blurFunction()">
                        <p style="font-size:0.9vw;">When you leave the input field, a function is triggered which transforms the 
                        input text to upper case.</p>
                        <p>onfocus</p>
                        Enter your name: <input type="text" onfocus="focusFunction(this)">
                        <p style="font-size:0.9vw;">When the input field gets focus, a function changes the background-color.</p>
                        <p>onfocusin</p>
                        Enter your name: <input type="text" onfocusin="onfocusFunction(this)">
                        <p style="font-size:0.9vw;">When the input field gets focus, a function changes the background-color.</p>
                        <p>onfocusout</p>
                        Enter your name: <input type="text" id="fname_1aa" onfocusout="focusOutFunction()">
                        <p style="font-size:0.9vw;">When you leave the input field, a function transforms the input text to upper case.</p>
                    </div>
                    <script>
                        function blurFunction() {
                            let x = document.getElementById("fname_1a");
                            x.value = x.value.toUpperCase();
                        }
                        function focusFunction(x) {
                            x.style.background = "yellow";
                        }
                        function onfocusFunction(x) {
                            x.style.background = "green";
                        }
                        function focusOutFunction() {
                            let x = document.getElementById("fname_1aa");
                            x.value = x.value.toUpperCase();
                        }
                    </script>
                

FocusEvent properties

relatedTarget : the element that triggered the event


Form events

top

Form events are:

onblur : when an element loses focus.

onchange : the content of a form element changes (for "input", "select" and "textarea").

onfocus : an element gets focus.

onfocusin : when an element is about to get focus.

onfocusout : the element is about to lose focus.

oninput : the user input on an element.

oninvalid : an element is invalid.

onreset : a form is reset.

onsearch : the user writes something in a search field (for input ="search")

onselect : the user selects some text (for "input" and "textarea").

onsubmit : a form is submitted.

Examples: form events

onblur

Enter your name:

When you leave the input field, a function is triggered which transforms the input text to upper case.

onchange

Enter your name:

When you leave the input field, a function is triggered which transforms the input text to upper case.

onfocus

Choose which browser you prefer:

onfocusin

Enter your name:

When the input field gets focus, a function is triggered which changes the background-color.

onfocusout

Enter your name:

When the input field gets focus, a function is triggered which changes the background-color.

oninput

Enter your name:

When you leave the input field, a function is triggered which transforms the input text to upper case.

Write something in the text field to trigger a function.

oninvalid

Name:

If you click submit, without filling out the text field, an alert message will occur.

onreset

Enter your name:

onsearch

Write something in the search field and press "ENTER".

onselect

Select some of the text:

onsubmit

Enter your name:
code:
                    <div class="spec">
                        <p>onblur</p>
                        <a>Enter your name:</a><input type="text" id="fname" onblur="firstEvent()">
                        <p style="font-size: 0.9vw">When you leave the input field, a function is triggered which transforms the input text 
                        to upper case.</p>
                        <p>onchange</p>
                        <a>Enter your name:</a>
                        <input type="text" id="fname1" onchange="secondEvent()">
                        <p style="font-size: 0.9vw">When you leave the input field, a function is triggered which transforms the input text 
                        to upper case.</p>
                        <p>onfocus</p>
                        <form>Choose which browser you prefer:
                            <select id="browsers" onchange="preferedBrowser()">
                                <option value="Chrome">Chrome</option>
                                <option value="Internet Explorer">Internet Explorer</option>
                                <option value="Firefox">Firefox</option>
                            </select>
                        </form>
                        <p>onfocusin</p>
                        <a>Enter your name:</a><input type="text" onfocus="thirdEvent(this)">
                        <p style="font-size: 0.9vw">When the input field gets focus, a function is triggered which changes the background-color.</p>
                        <p>onfocusout</p>
                        <a>Enter your name:</a><input type="text" onfocusin="fourthEvent(this)">
                        <p style="font-size: 0.9vw">When the input field gets focus, a function is triggered which changes the background-color.</p>
                        <p>oninput</p>
                        <a>Enter your name:</a><input type="text" id="fullname" onfocusout="fifthEvent()">
                        <p style="font-size: 0.9vw">When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
                        <p>Write something in the text field to trigger a function.</p>
                        <input type="text" id="myInput" oninput="inputEvent()">
                        <p id="event10"></p>
                        <p>oninvalid</p>
                        <div>
                            <form action="/action_page.php" method="get">
                                <a>Name:</a> <input type="text" oninvalid="alert('You must fill out the form!');" name="fname" required>
                                <input type="submit" value="Submit">
                            </form>
                            <p style="font-size: 0.9vw">If you click submit, without filling out the text field, an alert message will occur.</p>
                        </div>
                        <p>onreset</p>
                        <div>
                            <form onreset="message()">
                                <a>Enter your name:</a><input type="text" size="20">
                                <input type="reset">
                            </form>
                        </div>
                        <p>onsearch</p>
                        <div>
                            <p>Write something in the search field and press "ENTER".</p>
                            <input type="search" id="mySearch" onsearch="searchEvent()">
                            <p id="event11"></p>
                        </div>
                        <p>onselect</p>
                        <div>
                            <a> Select some of the text: </a><input type="text" value="How are you doing!" onselect="selectEvent()">
                            <p id="event12"></p>
                        </div>
                        <p>onsubmit</p>
                        <div>
                            <form onsubmit="confirmInput()" action="https://www.lwitters.com/">
                                <a>Enter your name: </a><input id="fname2" type="text" size="20">
                                <input type="submit">
                            </form>
                        </div>
                    </div>
                    <script>
                        function firstEvent() {
                            var x = document.getElementById("fname");
                            x.value = x.value.toUpperCase();
                        }
                        function secondEvent() {
                                var x = document.getElementById("fname1");
                                x.value = x.value.toUpperCase();
                            }
                        function preferedBrowser() {
                            prefer = document.forms[1].browsers.value;
                            alert("You prefer browsing internet with " + prefer);
                        }
                        function thirdEvent(x) {
                            x.style.background = "yellow";
                        }
                        function fourthEvent(x) {
                            x.style.background = "lightgreen";
                        }
                        function fifthEvent() {
                            var x = document.getElementById("fullname");
                            x.value = x.value.toUpperCase();
                        }
                        function inputEvent() {
                            var x = document.getElementById("myInput").value;
                            document.getElementById("event10").innerHTML = "You wrote: " + x;
                        }
                        function message() {
                            alert("This alert box was triggered by the onreset event handler");
                        }
                        function searchEvent() {
                            var x = document.getElementById("mySearch");
                            document.getElementById("event11").innerHTML = "You are searching for: " + x.value;
                        }
                        function selectEvent() {
                            document.getElementById("event12").innerText = "You selected some text!";
                        }
                        function confirmInput() {
                            fname = document.forms[4].fname2.value;
                            alert("Hello " + fname + "! You will now be redirected to www.lwitters.com");
                        }
                    </script>
                

HashChangeEvent Object: events when anchor of an URL changed

top

HashChange events are:

onhashchange : there has been changes to the anchor part of a URL

Examples

Click the button to change the anchor part of the current URL to #part5

code:
                    <div class="spec">
                        <p>Click the button to change the anchor part of the current URL to #part5</p>
                        <button onclick="changePart()">Try it</button>
                        <p id="event_010"></p>
                    </div>
                    <script>
                        // Using the location.hash property to change the anchor part
                        function changePart() {
                            location.hash = "part5";
                            var x = location.hash;
                            document.getElementById("event_010").innerHTML = "The anchor part is now: " + x;
                        }
                        // Alert some text if there has been changes to the anchor part
                        //function changeFunction() {
                        //alert("The anchor part has changed!");
                        //}
                    </script>
                

HashChangeEvent properties:

newURL : the URL of the document, after the hash has been changed

oldURL : the URL of the document, before the hash was changed


InputEvent Object: events when an input element is changed

top

Input events are:

oninput: the content (value) of an input element is changed.

Examples: input events

Write something in the text field to trigger a function.

code:
                    <div class="spec">
                        <p>Write something in the text field to trigger a function.</p>
                        <input type="text" id="myInput1" oninput="inputFunction()">
                        <p id="event_020"></p>
                    </div>
                    <script>
                        function inputFunction() {
                            let text_input = document.getElementById("myInput1").value;
                            document.getElementById("event_020").innerHTML = "You wrote: " + text_input;
                            }
                    </script>
                

InputEvent properties:

data : the inserted characters

dataTransfer : an object containing information about the inserted/deleted data

inputType : the type of the change (i.e "inserting" or "deleting")

isComposing : if the state of the event is composing or not


KeyboardEvent Object: events when a user presses a key on the keyboard

top

Keyboard events:

onkeydown : when the user is pressing a key down.

onkeyup : the user releases a key.

onkeypress : the moment the user starts pressing a key.

Examples: keyboard events

A function is triggered when the user is pressing a key in the input field.

A function is triggered when the user releases a key in the input field. The function transforms the character to upper case.

Enter your name:
Enter your name:

A function is triggered when the user is pressing a key in the input field.

code:
                <div>
                    <p>A function is triggered when the user is pressing a key in the input field.</p>
                    <input type="text" onkeydown="keyDown()">
                    <p id="key1" style="color:red"></p>
                </div>
                <div>
                    <p>A function is triggered when the user releases a key in the input field. The function transforms the character 
                    to upper case.</p>
                    <a>Enter your name: </a><input type="text" id="fname4" onkeyup="keyUp()">   
                </div>
                <div>
                    <form>
                        <a>Enter your name: </a>
                        <input type="text" name="myInput" id="key2" onkeyup="writeMessage()" size="15">
                        <input type="text" id="key3" name="mySecondInput" size="20">
                    </form>    
                </div>
                <div>
                    <p>A function is triggered when the user is pressing a key in the input field.</p>
                    <input type="text" onkeypress="keyPress()">    
                    <p id="key4" style="color:blue"></p>
                </div>
    
            </div>
            <script>
                function keyDown() {
                    // alert("You pressed a key inside the input field");
                    document.getElementById("key1").innerHTML = "You pressed a key inside the input field";
                }
                function keyUp(){
                    var Ax = document.getElementById("fname4");
                    Ax.value = Ax.value.toUpperCase();
                }
                function writeMessage() {
                    document.getElementById("key3").value = document.getElementById("key2").value;
                }
                function keyPress() {
                        // alert("You pressed a key inside the input field");
                        document.getElementById("key4").innerHTML = "You pressed a key inside the input field";
                    }
            </script>
            

KeyboardEvent properties:

altKey : if the ALT key was pressed

code : the code of the key that triggered the event

ctrlKey : if the CTRL key was pressed

isComposing : if the state of the event is composing or not

key : the value of the key that triggered the event

location : the location of a key on the keyboard or device

metaKey : if the META key was pressed

repeat : if a key is being hold down repeatedly, or not

shiftKey : if the SHIFT key was pressed


MouseEvent Object: events when the mouse interacts with the HTML document

top

Mouse events are:

onclick : the event occurs when the user clicks on an element.

oncontextmenu: the user right-clicks on an element to open a context menu.

The contextmenu attribute only works in Firefox!!

ondblclick: the user double-clicks on an element.

onmousedown : the user presses a mouse button over an element.

onmouseup : the user releases a mouse button while over an element.

onmouseenter : the pointer moves onto an element.

onmouseleave : the pointer moves out of an element.

onmousemove : the pointer is moving while it is over an element.

onmouseover : when the pointer is moved onto an element or one of its children.

onmouseout : the user moves the mouse pointer out of an element or one of its children.

Examples: mouse events

onclick

ondblclick

double-click this paragraph to trigger a function.

mousedown - mouseup

Click the text! The mouseDown() function is triggered when the mouse button is pressed down over this paragraph, and sets the color of the text to red. The mouseUp() function is triggered when the mouse button is released, and sets the color of the text to green.

Click this text to change the color. A function, with parameters, is triggered when the mouse button is pressed down, and again, with other parameters, when the mouse button is released.

Click this text (with one of your mouse-buttons). Read alert!!

0 specifies the left mouse-button
1 specifies the middle mouse-button
2 specifies the right mouse-button

onmouseenter - onmouseleave

zoom-in

The function bigImg() is triggered when the user moves the mouse pointer onto the image.

The function normalImg() is triggered when the mouse pointer is moved out of the image.

movemouse

Mouse over the rectangle above, and get the coordinates of your mouse pointer.

When the mouse is moved over the div, the p element will display the horizontal and vertical coordinates of your mouse pointer, whose values are returned from the "clientX" and "clientY" properties on the MouseEvent object.

onmouseover - onmouseout

Mouse over this text - onmouseover

code:
                    <div class="spec">
                        <p>onclick</p>
                        <button onclick="this.innerHTML=Date()">The time is?</button>
                        <p>ondblclick</p>
                        <p ondblclick="doubleClick()" style="font-size: 1vw; margin-left:2vw;">double-click this paragraph to
                         trigger a function.</p>
                        <p style="color:red; font-size: 1vw;" id="event02"></p>
                        <p>mousedown - mouseup</p>
                        <p class="spec" id="event03" onmousedown="mouseDown()" onmouseup="mouseUp()" style="font-size: 1vw;">
                        Click the text! The mouseDown() function is triggered when the mouse button is pressed down over this paragraph, 
                        and sets the color of the text to red. The mouseUp() function is triggered when the mouse button is released, and 
                        sets the color of the text to green.</p>
                        <p class="spec" onmousedown="myFunction7(this,'red')" onmouseup="myFunction7(this,'blue')"style="font-size: 1vw;">
                        Click this text to change the color. A function,  with parameters, is triggered when the mouse button is pressed down, 
                        and again, with other parameters, when the mouse button is released.</p>    
                        <p class="spec" onmousedown="WhichButton(event);"style="font-size: 1vw;">Click this text (with one of your 
                        mouse-buttons). 
                        Read alert!!</p>
                        <p class="spec-2"style="font-size: 1vw;">
                            0 specifies the left mouse-button<br>
                            1 specifies the middle mouse-button<br>
                            2 specifies the right mouse-button
                        </p>
                        <p>onmouseenter - onmouseleave</p>
                        <div>
                            <img class="spec" onmouseenter="bigImg(this)" onmouseleave="normalImg(this)" border="0" src="../pics/zoom-in.png"
                             alt="zoom-in" width="32" height="32">
                            <p style="margin-left: 2vw; font-size: 1vw;">The function bigImg() is triggered when the user moves the mouse 
                            pointer onto the image.</p>
                            <p style="margin-left: 2vw; font-size: 1vw;">The function normalImg() is triggered when the mouse pointer is 
                            moved out of the image.</p>
                        </div>
                        <p>movemouse</p>
                        <div class="spec">
                            <div id="event04" onmousemove="moveMouse(event)" onmouseout="clearCoor()"></div>           
                            <p style="font-size: 1vw;">Mouse over the rectangle above, and get the coordinates of your mouse pointer.</p>
                            <p style="font-size: 1vw;">When the mouse is moved over the div, the p element will display the horizontal and 
                            vertical coordinates of your mouse pointer, whose values are returned from the "clientX" and "clientY" properties on the 
                            MouseEvent object.</p>
                            <p id="event05"  style="font-size: 1vw;"></p>
                        </div>
                        <p>onmouseover - onmouseout</p>
                        <p onmouseover="style.color='red'" onmouseout="style.color='blue'"  style="font-size: 1vw; margin-left: 2vw;">Mouse over
                         this text - onmouseover</p>
                    </div>
                    <script>
                         function doubleClick() {
                            document.getElementById("event02").innerHTML = "Hello World";
                        }
                        function mouseDown() {
                            document.getElementById("event03").style.color = "red";
                        }
                        function mouseUp() {
                            document.getElementById("event03").style.color = "green";
                        }
                        function myFunction7(elmnt, clr) {
                            elmnt.style.color = clr;
                        }
                        function WhichButton(event) {
                            alert("You pressed button: " + event.button)
                        }
                        function bigImg(x) {
                            x.style.height = "64px";
                            x.style.width = "64px";
                        }
        
                        function normalImg(x) {
                            x.style.height = "32px";
                            x.style.width = "32px";
                        }
                        function moveMouse(e) {
                            var xx = e.clientX;
                            var xy = e.clientY;
                            var coor = "Coordinates : (" + xx + "," + xy + ")";
                            document.getElementById("event05").innerHTML = coor;
                        }
                        function clearCoor() {
                            document.getElementById("event05").innerHTML = "";
                        }
                    </script>

                

MouseEvent properties:

altKey : if the ALT key was pressed

button : which mouse button is pressed

buttons : which mouse buttons were pressed

clientX : the X coordinate of the mouse pointer (window relative)

clientY : the Y coordinate of the mouse pointer (window relative)

ctrlKey : if the CTRL key was pressed

p : the p about an event

metaKey : if the META key was pressed

offsetX : the X coordinate of the mouse pointer (target relative)

offsetY : the Y coordinate of the mouse pointer (target relative)

pageX : the X coordinate of the mouse pointer (document relative)

pageY : the Y coordinate of the mouse pointer (document relative)

relatedTarget : the element that triggered the mouse event

screenX : the X coordinate of the mouse pointer (screen relative)

screenY : The Y coordinate of the mouse pointer (screen relative)

shiftKey : if the SHIFT key was pressed

The clientX property returns the horizontal client coordinate of the mouse pointer when a mouse event occurs. The clientX property is read-only. The client area is the current window.

The clientY property returns the vertical client coordinate of the mouse pointer when a mouse event occurs. The clientY property is read-only. The client area is the current window.


PageTransitionEvent Object: events when a user navigates to or from a webpage

top

PageTransition events

pagehide : a user navigates away from a webpage

Syntax:

in HTML: <element onpagehide="myScript"></element>

in JavaScript: object.onpagehide = function(){myScript};

in JavaScript using the addEventListener() method: object.addEventListener("pagehide", myScript);

pageshow : a user navigates to a webpage

Syntax:

in HTML: <element onpageshow="myScript"></element>

in JavaScript: object.onpageshow = function(){myScript};

in JavaScript using the addEventListener() method: object.addEventListener("pageshow", myScript);

PageTransitionEvent propertird

persisted : if the webpage was cached by the browser


PopStateEvent Object: events that occur when the window's history changes

top

PopState events are:

popstate : the window's history changes

PopStateEvents properties:

state : an object containing a copy of the history entries


ProgressEvent Object: events when loading external resources

top

Progress events are:

onerror : an error occurs while loading an external file

Syntax:

in HTML : <element onerror="myScript"></element>

in JavaScript : object.onerror = function(){myScript};

in JavaScript using the addEventListener() method: object.addEventListener("error", myScript);

onloadstart : the browser starts looking for the specified file

Syntax:

in HTML : <element onloadstart="myScript"></element>

in JavaScript : object.onloadstart = function(){myScript};

in JavaScript using the addEventListener() method: object.addEventListener("loadstart", myScript);

ProgressEvents propertires:

lengthComputable : if the length of the progress can be computable or not

loaded : how much work has been loaded

total : the total amount that will be loaded


StorageEvent Object: events when there is changes in the window's storage area

top

Storage events are:

storage : a Web Storage area is updated

Syntax: event.url

StoragEvent properties:

key : the key of the storage item

newValue : the new value of the storage item

oldValue : the old value of the storage item

storageArea : the affected storage object

url : the URL of the changed item's document


TouchEvent Object: events when a user touches a touch-based device

top

Touch events are:

ontouchcancel : a touch is interrupted

Syntax:

in HTML : <element ontouchchannel ="myScript"></element>

in JavaScript : object.ontouchchannel = myScript;

in JavaScript using the addEventListener() method: object.addEventListener("touchchannel", myScript);

ontouchend : a finger is removed from a touch screen

Syntax:

in HTML : <element ontouchend="myScript"></element>

in JavaScript : object.ontouchendr = myScript;

in JavaScript using the addEventListener() method: object.addEventListener("touchend", myScript);

ontouchmove :a finger is dragged across the screen

Syntax:

in HTML : <element ontouchmove="myScript"></element>

in JavaScript : object.ontouchmove = myScript;

in JavaScript using the addEventListener() method: object.addEventListener("touchmove", myScript);

ontouchstart : A finger is placed on a touch screen

Syntax:

in HTML : <element ontouchstart="myScript"></element>

in JavaScript : object.ontouchstart = myScript;

in JavaScript using the addEventListener() method: object.addEventListener("touchstart", myScript);

TouchEvent properties:

altKey : if the ALT key was pressed when the event was triggered

changedTouches : a list of the touch objects whose state changed between this and the previous touch

ctrlKey : if the CTRL key was pressed when the event was triggered

metaKey : if the META key was pressed when the event was triggered

shiftKey : if the SHIFT key was pressed when the event was triggered

targetTouches : a list of the touch objects that are in contact with the surface and where the touchstart event occured on the same target element as the current target element

touches : a list of the touch objects that are currently in contact with the surface


TransitionEvent Object: events when a CSS transition runs

top

Transition events are:

transitionend : a CSS transition has completed

Syntax:

object.addEventListener("webkitTransitionEnd", myScript); // Code for Safari 3.1 to 6.0
object.addEventListener("transitionend", myScript); // Standard syntax

TransitionEvent properties:

propertyName : the name of the transition

elapsedTime : the number of seconds a transition has been running

pseudoElement : the name of the pseudo-element of the transition


UiEvent Object: events that are triggered from the user interface

top

Ui events are:

abort : the loading of a media is aborted

Syntax:

in HTML : <element onabort="myScript"></element>

in JavaScript : object.onabort = function(){myScript};

in JavaScript using the addEventListener() method: object.addEventListener("abort", myScript);

beforeunload : a document is about to be unloaded

Syntax:

in HTML : <element onbeforeunload="myScript"></element>

in JavaScript : object.onbeforeunload = function(){myScript};

in JavaScript using the addEventListener() method: object.addEventListener("beforeunload", myScript);

error : an error occurs during the loading of a media file

Syntax:

in HTML : <element onerror="myScript"></element>

in JavaScript : object.onerror = function(){myScript};

in JavaScript using the addEventListener() method: object.addEventListener("error", myScript);

load : an object has loaded

Syntax:

in HTML : <element onload="myScript"></element>

in JavaScript : object.onload = function(){myScript};

in JavaScript using the addEventListener() method: object.addEventListener("load", myScript);

resize : the document view is resized

Syntax:

in HTML : <element onresize="myScript"></element>

in JavaScript : object.onresize = function(){myScript};

in JavaScript using the addEventListener() method: object.addEventListener("resize", myScript);

scroll : an element's scrollbar is scrolled

Syntax:

in HTML : <element onscroll="myScript"></element>

in JavaScript : object.onscroll = function(){myScript};

in JavaScript using the addEventListener() method: object.addEventListener("scroll", myScript);

select : a user selects text

Syntax:

in HTML : <element onselect="myScript"></element>

in JavaScript : object.onselect = function(){myScript};

in JavaScript using the addEventListener() method: object.addEventListener("select", myScript);

unload : a page has unloaded (for )

Syntax:

in HTML : <element onunload="myScript"></element>

in JavaScript : object.onunload = function(){myScript};

in JavaScript using the addEventListener() method: object.addEventListener("unload", myScript);

UiEvent properties:

detail : the p about an event

view : the Window object where the event occurred


WheelEvent Object: events when the mouse wheel is scrolling

top

Wheel events are:

onwheel : the mouse wheel rolls over an element

Syntax:

in HTML : <element onwheel="myScript"></element>

in JavaScript : object.onwheel = function(){myScript};

in JavaScript using the addEventListener() method: object.addEventListener("wheel", myScript);

WheelEvent properties:

deltaX : the horizontal (x-axis) scroll amount of the wheel

deltaY : the vertical (y-axis) scroll amount of the wheel

deltaZ : the z-axis scroll amount of the wheel

deltaMode : the unit of measurements (pixels, lines or pages)


Media events

top

onabort — media loading is aborted.

oncanplay — the browser can start playing media (e.g. a file has buffered enough).

oncanplaythrough — when browser can play through media without stopping.

ondurationchange — the duration of the media changes.

onended — the media has reach its end.

onerror — happens when an error occurs while loading an external file.

onloadeddata — media data is loaded.

onloadedmetadata — meta data (like dimensions and duration) are loaded.

onloadstart — browser starts looking for specified media.

onpause — media is paused either by the user or automatically.

onplay — the media has been started or is no longer paused.

onplaying — media is playing after having been paused or stopped for buffering.

onprogress — browser is in the process of downloading the media.

onratechange — the playing speed of the media changes.

onseeked — user is finished moving/skipping to a new position in the media.

onseeking — the user starts moving/skipping.

onstalled — the browser is trying to load the media but it is not available.

onsuspend — browser is intentionally not loading media.

ontimeupdate — the playing position has changed (e.g. because of fast forward).

onvolumechange — media volume has changed (including mute).

onwaiting — media paused but expected to resume (for example, buffering).


Other events

top

transitionend — fired when a CSS transition has completed.

onmessage — a message is received through the event source.

onoffline — browser starts to work offline.

ononline — the browser starts to work online.

onpopstate — when the window's history changes.

onshow — a "menu" element is shown as a context menu.

onstorage — a Web Storage area is updated.

ontoggle - the user opens or closes the "p" element.

onwheel — mouse wheel rolls up or down over an element.

ontouchcancel — screen touch is interrupted.

ontouchend — user finger is removed from a touch screen.

ontouchstart — finger is placed on touch screen.


Errors

top

try — let you define a block of code to test for errors.

catch — set up a block of code to execute in case of an error.

throw — create custom error messages instead of the standard JavaScript errors.

finally — let you execute code, after try and catch, regardless of the result.


Error name values

top

name — sets or returns the error name.

message — sets or returns an error message in string from.

EvalError — an error has occurred in the eval() function.

RangeError — a number is “out of range”.

ReferenceError — an illegal reference has occurred.

SyntaxError — a syntax error has occurred.

TypeError — a type error has occurred.

URIError — an encodeURI() error has occurred.


Frame events

top

onabort — the loading of a media is aborted.

onbeforeunload — event occurs before the document is about to be unloaded.

onerror — an error occurs while loading an external file.

onhashchange — there have been changes to the anchor part of a URL.

onload — when an object has loaded.

onpagehide — the user navigates away from a webpage.

onpageshow — when the user navigates to a webpage.

onresize — the document view is resized.

onscroll — an element's scrollbar is being scrolled.

onunload — event occurs when a page has unloaded.


Events examples

top

JavaScript.info - examples

examples
event handlers: HTML attribute:
                <input value="Click me" onclick="alert('Click!')" type="button">

                <script>
                    function countRabbits() {
                    for(let i=1; i<=3; i++) {
                        alert("Rabbit number " + i);
                    }
                    }
                </script>
                <input type="button" onclick="countRabbits()" value="Count rabbits!">
            
event handlers: DOM property:
                <input id="elem" type="button" value="Click me">
                <script>
                elem.onclick = function() {
                    alert('Thank you');
                };
                </script>

                <input type="button" id="elem" onclick="alert('Before')" value="Click me">
                <script>
                elem.onclick = function() { // overwrites the existing handler
                    alert('After'); // only this will be shown
                };
                </script>
            
accessing the element: this:
                <button onclick="alert(this.innerHTML)">Click me</button> // Click me
            
addEventListener:
                <input id="elem" type="button" value="Click me"/>
                <script>
                function handler1() {
                    alert('Thanks!');
                };
                function handler2() {
                    alert('Thanks again!');
                }
                elem.onclick = () => alert("Hello");
                elem.addEventListener("click", handler1); // Thanks!
                elem.addEventListener("click", handler2); // Thanks again!
                </script>
            
event object:
                <input type="button" value="Click me" id="elem">
                <script>
                    elem.onclick = function(event) {
                        // show event type, element and coordinates of the click
                        alert(event.type + " at " + event.currentTarget);
                        alert("Coordinates: " + event.clientX + ":" + event.clientY);
                    };  
                </script>
            
object handlers: handleEvent:
                <button id="elem">Click me</button>
                <script>
                    let obj = {
                        handleEvent(event) {
                            alert(event.type + " at " + event.currentTarget);
                        }
                    };
                    elem.addEventListener('click', obj);
                </script>