Event handlers should be used in the correct way; it is advisable not to write them directly in tag attributes, but to install event handlers in included files with JavaScript code. If the jQuery library is used, then the name of the handlers must be written without the on prefix.
click / onclick
– click on an element; occurs when the element is clicked with the left mouse button (on devices with touch screens it occurs when touched).

Pop-up recording options
<input value="Press me" onclick="alert('Click!')" type="button">
<a href="#" onclick="alert('Example 1 worked'); return false;">Example 1</a>
Sequence of numbers starting from 1
<script>
function countRabbits() {
for(let i=1; i<=3; i++) {
alert("Rabbit number " + i);
}
}
</script>
<input type="button" onclick="countRabbits()" value="Counting rabbits!">
<input id="elem" type="button" value="Press me!">
<script>
elem.onclick = function() {
alert('Thanks');
};
</script>
<input type="button" id="button" value="Button">
<script>
button.onclick = function() {
alert('Click!');
};
</script>
Displays “Press me” in a pop-up window – the contents of the button
<button onclick="alert(this.innerHTML)">Press me</button>
Multiple popup event handlers
<input id="elem" type="button" value="Press 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>
Getting mouse coordinates from an event object
<input type="button" value="Press me" id="elem">
<script>
elem.onclick = function(event) {
// display event type, element and click coordinates
alert(event.type + " на " + event.currentTarget);
alert("Coordinates: " + event.clientX + ":" + event.clientY);
};
</script>
Changing the background of an object
<button>Change color</button>
<script>
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() * (number + 1));
}
btn.onclick = function () {
const rndCol =
"rgb(" + random(255) + "," + random(255) + "," + random(255) + ")";
document.body.style.backgroundColor = rndCol;
};
</script>
<button onclick="bgChange()">Press me</button>
<script>
function bgChange() {
const rndCol =
"rgb(" + random(255) + "," + random(255) + "," + random(255) + ")";
document.body.style.backgroundColor = rndCol;
}
</script>
Changing the background of an object div
<div id='myDiv'>Color change element</div>
<button onclick='changeColor()'>Change color</button>
<script>
function changeColor() {
document.getElementById('myDiv').style.backgroundColor = 'red';
}
</script>
Change link color
<script>
function ChangeColor(Element) {
if (Element.style.color == 'green') Element.style.color = 'red';
else Element.style.color = 'green';
return false;
}
</script>
<a href="#" style="color: green;" onclick="return ChangeColor(this);">Change color</a>
Form Validation
<form>
<div>
<label for="fname">Name: </label>
<input id="fname" type="text" />
</div>
<div>
<label for="lname">Last name: </label>
<input id="lname" type="text" />
</div>
<div>
<input id="submit" type="submit" />
</div>
</form>
<p></p>
<script>
var form = document.querySelector("form");
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
var submit = document.getElementById("submit");
var para = document.querySelector("p");
form.onsubmit = function (e) {
if (fname.value === "" || lname.value === "") {
e.preventDefault();
para.textContent = "Both fields must be filled in!";
}
};
</script>
Intercepting events from CSS in video with the stopPropagation() function, which, when called in an object’s event handler, causes the handler to be executed, but the event does not bubble up further down the chain
<button>Display video</button>
<div class="hidden">
<video>
<source src="rabbit320.mp4" type="video/mp4" />
<source src="rabbit320.webm" type="video/webm" />
<p>
Your browser doesn't support HTML5 video. Here is a
<a href="rabbit320.mp4">link to the video</a> instead.
</p>
</video>
</div>
div { position: absolute;
top: 50%;
transform: translate(-50%,-50%);
... }
.hidden {
left: -50%;
}
.showing {
left: 50%;
}
<script>
var videoBox = document.querySelector("div");
var video = document.querySelector("video");
videoBox.onclick = function () {
videoBox.setAttribute("class", "hidden");
};
video.onclick = function () {
video.play();
};
video.onclick = function (e) {
e.stopPropagation();
video.play();
};
</script>
<p style="text-align: justify;">Show and hide text</p>
<button onclick='toggleVisibility()'>Show/Hide</button>
<div id='hiddenDiv' style='display:none'>Hide text</div>
<script>
function toggleVisibility() {
let element = document.getElementById('hiddenDiv');
if (element.style.display === 'none') {
element.style.display = 'block';
} else {
element.style.display = 'none';
}
}
</script>
Loading data via AJAX, to load data from the server without reloading the page
function fetchData() {
// Here's your code for the AJAX request
}
<onclick="fetchData()">Download data</button>
Changing the link name from On to Off
<script>
//wait for the page to load completely
window.onload = function () {
//get the element identifier
var a = document.getElementById('switch');
//hang an event on it
a.onclick = function() {
//we perform some actions
if (this.innerHTML=='On') this.innerHTML = 'Off';
else this.innerHTML = 'On';
//prevent clicking on href link
return false;
}
}
</script>
<a id="switch" href="#">On</a>
onabort
– interruption of playback. The onabort event occurs when the download of audio or video is interrupted. The onabort event occurs only when the download is aborted, not when an error occurs. Applies to elements audio, embed, img, object, video.
Notification that video loading has been interrupted
<video id="myVideo" onabort="alert('Video load aborted')">
Notification that image loading has been interrupted
<img id="myImage" src="example.jpg" onabort="imageAborted()">
<script>
function imageAborted() {
alert("Image load was aborted by the user.");
}
</script>
Notification that form submission has been interrupted
<form id="myForm">
<input type="text" placeholder="Enter your name">
<input type="submit" value="Submit">
</form>
<script>
var form = document.getElementById("myForm");
form.addEventListener("abort", formAborted);
function formAborted() {
alert("Form submission was aborted by the user.");
}
</script>
onafterprint – printing finished
The onafterprint event occurs when the page begins printing. The onafterprint event occurs when the print dialog is closed. The browser runs onafterprint and onbeforeprint so that notes, explanations and comments can be added to the printing process. Apply to body.
<body onafterprint="myFunction()">
onautocomplete – form autofill completed
An attribute with which the form can be filled out in one click – the browser will insert the values into the appropriate fields.
<form> <label for="name">Name:</label> <input type="text" id="name" name="name" autocomplete="on"> </form>
onautocompleteerror – error when autofilling form
onbeforeprint – preparation for printing
onbeforeunload – document uploaded
When a user leaves the page, we can ask him if he really wants to leave. Handling the beforeunload event is responsible for this. The event occurs before the unload page unload event. This event allows the web page to trigger a confirmation dialog asking the user if they really want to leave the page. If the user confirms, the browser navigates to a new page, otherwise it cancels the navigation. According to the specification, to display a confirmation dialog, the event handler must call preventDefault() on the event. Apply to body.
<body onbeforeunload="return myFunction()">
<script>
function myFunction() {
return "Are you sure you want to close this page?...";
}
</script>
onblur – loss of focus
The focus event is called when the element is focused, and the blur event is called when the element loses focus. focus/blur support is guaranteed for elements that the visitor can interact with: button, input, select, a, etc. On the other hand, div, span, table formatting elements cannot receive focus by default. The elem.focus() method doesn’t work for them and the focus/blur events never fire. This can be changed with the tabindex HTML attribute.
Validation (checking) of entered data with an inscription under the form
<style>
.invalid { border-color: red; }
#error { color: red }
</style>
<script>
input.onblur = function() {
if (!input.value.includes('@')) { // not email
input.classList.add('invalid');
error.innerHTML = 'Please enter a correct email.'
}
};
input.onfocus = function() {
if (this.classList.contains('invalid')) {
// We remove the error indicator, because the user wants to re-enter data
this.classList.remove('invalid');
error.innerHTML = "";
}
};
</script>
Your email: <input type="email" id="input">
<div id="error"></div>
Validation (checking) of entered data by filling the form with color
<style>
.error {
background: red;
}
</style>
<script>
input.onblur = function() {
if (!this.value.includes('@')) { // не email
// show error
this.classList.add("error");
// ...and return focus back
input.focus();
} else {
this.classList.remove("error");
}
};
</script>
Your email: <input type="email" id="input">
<input type="text" style="width:280px" placeholder="enter an incorrect email and click here">
Changing form text CLICK HERE
<input type="text" value="CLICK HERE" />
<script>
let input = document.querySelector("input");
input.onblur = inputBlur;
input.onfocus = inputFocus;
function inputBlur() {
input.value = "Focus has been lost";
}
function inputFocus() {
input.value = "Focus is here";
}
</script>
Checking the shape with a frame outline
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>Event onblur</title>
<style>
.warning {
background-color: #ffe;
outline: 1px solid #dc143c;
}
</style>
<script>
function warning(field) {
if (field.value == '') field.classList.add('warning');
else field.classList.remove('warning');
}
</script>
</head>
<body>
<form>
<p><input placeholder="Name" onblur="warning(this)"></p>
<p><input placeholder="Last name" onblur="warning(this)"></p>
<p><input placeholder="Adress" onblur="warning(this)"></p>
</form>
</body>
</html>
Backlight when focusing without onblur
<style>
*!*input:focus*/!* {
background: #FA6;
outline: none; /* remove frame */
}
</style>
<input type="text">
<p>The focus selector will highlight an element when you focus on it and remove the border that the browser uses to highlight this element by default.</p>
Placeholder – a hint value inside an INPUT that automatically disappears when focused and exists until the visitor starts typing, without onblur
<style>
.my*!*::-webkit-input-placeholder*/!* {
color: red;
font-style: italic;
}
.my*!*::-moz-input-placeholder*/!* {
color: red;
font-style: italic;
}
.my*!*::-ms-input-placeholder*/!* {
color: red;
font-style: italic;
}
</style>
<input class="my" type="text" placeholder="E-mail">
oncancel – cancel action
Cancel the current operation on the device. Used for asynchronous device control. If you perform this function before starting an operation, the operation will be canceled.
Device.Cancel ();
oncanplay
– you can start playing the specified media file
The oncanplay event occurs when the browser can start playing the specified audio/video (when it is buffered enough to start). During the audio/video loading process, the following events occur in this order: onloadstart, ondurationchange, onloadedmetadata, onloadeddata, onprogress, oncanplay, oncanplaythrough
Execute JavaScript when the video is ready to play:
<video oncanplay="myFunction()">
oncanplaythrough
– You can start playing the specified media file without having to stop for buffering. The oncanplaythrough event occurs when the browser judges that it can play the specified media without having to stop to buffer.
Execute JavaScript when the video can be played in its entirety, without stopping:
<video oncanplaythrough="myFunction()">
onchange – change value
The onchange event occurs when the value of an element has been changed. For radio buttons and checkboxes, the onchange event occurs when the checked state changes. This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the element’s value changes, while onchange occurs when the element loses focus after the content has changed. Another difference is that the onchange event also works on the select element. A handler for the onchange event, which fires when the element’s value has changed and it has lost focus. For AudioTrackList, VideoTrackList, and TextTrackList objects, this event occurs when one or more tracks are enabled/disabled. Executes JavaScript code when the change event occurs; that is, if a Select, Text, or Textarea field loses focus and its value has been changed.
type – Indicates the event type.
target – Indicates the object to which the event was originally sent
Run JavaScript when the user changes the selected option of a select element:
<select onchange="myFunction()">
Here userName is a text field. If the user changes the text and leaves the field, the onChange handler calls the checkValue function to confirm that userName is valid:
<INPUT TYPE="text" VALUE="" NAME="userName" onChange="checkValue(this.value)">
onclose – closing something
An event handler for close events is sent to the window. The OnClose event occurs when the dialog box is closed. You can create an event handler for the OnClose event to perform specific actions when the dialog box is closed. A handler for the close event, which is raised on dialog elements when they are closed and on WebSocket elements when the connection is completed.
oncontextmenu – opening context menu
The oncontextmenu event occurs when the user right-clicks an HTML element to open the context menu. Event handler property for the right-click event inside the window element. If the standard behavior is not prevented, the browser context menu is activated (There is a bug in IE8 that the context menu will not be activated if a contextmenu event handler is defined). The event will occur along with other right-click events and is independent of the element’s “contextmenu” attribute.
Run JavaScript when user right clicks on div element with context menu:
<div oncontextmenu="myFunction()" contextmenu="mymenu">
The code in this example changes the default behavior of the browser by disabling right-click.
document.oncontextmenu = function () {
//Use object "document" instead of "window" for compatibility with IE8.
return false;
};
window.addEventListener(
"contextmenu",
function (e) {
// Not compatible with IE versions earlier than 9
e.preventDefault();
},
false,
);
oncopy – copy completed
The oncopy event occurs when the user copies the content of an element. The oncopy event also occurs when the user copies an element, such as an image created using the img element. The oncopy event is mainly used for “input” elements with type=”text”. Triggered when inserting/copying/deleting text. If you cancel the browser action in their handlers, then insertion/copying/deleting will not occur. The inserted value cannot be obtained: at the time the event is triggered, the element still has the old value, and the new one is not available.
Execute JavaScript when copying some input element text:
<input type="text" oncopy="myFunction()" value="Try copying this text">
oncuechange – changing the label in the track element
A handler for the cuechange event, which fires when the TextTrack element changes the currently displayed timestamps (cue).
oncut – content has been cut
The oncut event occurs when the user cuts the content of an element. Although the oncut event is supported by all HTML elements, it is not actually possible to cut content in, for example, a p element UNLESS the element has set contenteditable to “true”. The oncut event is mainly used for input elements with type=”text”.
Execute JavaScript when cutting out some text in an input element:
<input type="text" oncut="myFunction()" value="Try shortening this text">
ondblclick – double click on an element
A handler for the dblclick event, which occurs when the left mouse button is double-clicked. The ondblclick event occurs when the user double-clicks an HTML element; that is, when the user double-clicks a form element or hyperlink.
type – Indicates the event type.
target – Indicates the object to which the event was originally sent.
layerX, layerY, pageX, pageY, screenX, screenY – Represents the location of the cursor when the event occurs.
which – Represents 1 for a left mouse click and 3 for a right mouse click.
modifiers – Contains a list of modifier keys pressed when the event occurs.
Run JavaScript when double clicking on an element p:
<p ondblclick="myFunction()">Double click me</p>
Here the alert dialog is displayed if the user double clicks the button:
<form>
<INPUT Type="button" Value="Double Click Me!" onDblClick="alert('You just double clicked me!')">
</form>
ondrag – dragging an element
The ondrag event occurs when an element or selected text is dragged. Drag and drop is a very common feature in HTML5. This is when you “grab” an object and drag it to another location.
type – Indicates the event type.
target – Indicates the object to which the event was originally sent.
data – Returns an array of strings containing the URLs of the released objects.
modifiers – Contains a list of modifier keys pressed when the event occurs.
screenX, screenY – Represents the location of the cursor when the event occurs.
Execute JavaScript when p element is dragged:
<p draggable="true" ondrag="myFunction(event)">Drag me!</p>
ondragend – element dragging completed
The ondragend event occurs when the user has finished dragging an element or text selection.
Run JavaScript when the user finishes dragging an element p:
<p draggable="true" ondragend="myFunction(event)">Drag me!</p>
ondragenter
– the element is dragged to a valid target zone. The ondragenter event occurs when the dragged element or selected text hits a valid delete target. The ondragenter and ondragleave events can help the user understand that the dragged element is about to enter or leave the drop target. This can be done, for example, by setting the background color when the dragged element hits the drag target, and clearing the color when the element is moved away from the target.
Execute JavaScript when the dragged element hits the drag target:
<div ondragenter="myFunction(event)"></div>
ondragexit
– exit drag and drop mode. A handler for the dragexit event, which occurs when an element is no longer the target of an element that can accept it.
ondragleave
– element leaves a valid target. The ondragleave event occurs when a dragged element or text selection leaves a valid drop target.
Execute JavaScript when the dragged element moves away from the drag target:
<div ondragleave="myFunction(event)"></div>
ondragover
– the element is dragged to a valid target point. The ondragover event occurs when a dragged element or selected text is dragged over a valid drop target. By default, data/elements cannot be removed from other elements. To allow deletion, we must disable element processing by default. This is done by calling the event.preventDefault() method on the ondragover event.
Execute JavaScript when an element is dragged on top of the drag target:
<div ondragover="myFunction(event)"></div>
ondragstart
– start of drag and drop operation. The ondragstart event occurs when the user starts dragging an element or selected text.
Run JavaScript when the user starts dragging an element p:
<p draggable="true" ondragstart="myFunction(event)">Drag me!</p>
ondrop
– the dragged element is released. The ondrop event occurs when a dragged element or selected text is dropped onto a valid drop target.
Execute JavaScript when a dragged element is removed in an element div:
<div ondrop="myFunction(event)"></div>
ondurationchange
– change in media length. The ondurationchange event occurs when the duration of the audio/video changes. When loading audio/video, the duration will change from “NaN” to the actual duration of the audio/video. During the audio/video loading process, the following events occur in this order: onloadstart, ondurationchange, onloadedmetadata, onloadeddata, onprogress, oncanplay, oncanplaythrough
Run JavaScript when video length has changed:
<video ondurationchange="myFunction()">
onemptied
– The file suddenly became unavailable. A handler for the emptied event, which occurs when the current playlist for an audio or video element is empty. Most often due to a connection failure.
onended
– playback is complete. The onended event occurs when the audio/video reaches the end. This event is useful for messages like “thanks for listening”, “thanks for watching”, etc.
Run JavaScript when audio ends:
<audio onended="myFunction()">
onerror
– an error occurred. The onerror event is fired if an error occurs while loading an external file (such as a document or image). When used on audio/video media, related events that occur when there is any disruption to the media loading process are: onabort, onemptied, onstalled, onsuspend.
The error event occurs only when a JavaScript syntax error or runtime error occurs, not when a browser error occurs. For example, if you try to install window.location.href=’notThere.html’, and file notThere.html does not exist, the resulting error message will be a browser message; hence onError will not intercept this message. However, the error event will be triggered by an invalid URL in the IMG tag or invalid image data.
window.onerror applies only to errors that occur in the window containing window.onerror, not to errors in other windows.
onError may have the following meanings:
– null to suppress all JavaScript error dialogs. Setting window.onerror to null means that your users won’t see JavaScript errors caused by your code.
– The name of the function that handles errors (arguments are the message text, URL, and line number with the error). To suppress standard JavaScript error dialog, this function must return true. See Example 3 below.
– Variable or property containing null or a valid function reference.
If you are writing an error handler function, you have three options for reporting errors:
– Track errors, but allow them to be reported via a standard JavaScript dialog (use an error handling function that returns false or does not return a value).
– Report errors yourself and disable the standard dialog (use an error handling function that returns true).
– Disable all error messages (set null in onError handler).
type – Indicates the event type.
target – Indicates the object to which the event was originally sent
Run JavaScript if an error occurs while loading an image:
<img src="image.gif" onerror="myFunction()">
Example 1: Handler with Null value. In this IMG tag, the onError=”null” code suppresses error messages if an error occurs while loading the image.
<IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2" onError="null">
Example 2: Null handler for a window. The onError handler for a window cannot be expressed via HTML. Therefore, you must enter everything necessary, in lower case, in the SCRIPT tag. The following code assigns null to the onError handler for the entire window, not just the Image object. This suppresses all JavaScript error messages, including those for the object Image.
<SCRIPT> window.onerror=null </SCRIPT> <IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2">
However, if the Image object has its own special onError handler, that handler will be executed when an error occurs with the image. This occurs because window.onerror=null suppresses JavaScript error messages, not onError handlers.
<SCRIPT>
window.onerror=null
function myErrorFunc() {
alert("The image had a nasty error.")
}
</SCRIPT>
<IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2" onError="myErrorFunc()">
In the following example, window.onerror=null suppresses all error messages. Without onerror=null the code will cause a stack overflow error because there is infinite recursion.
<SCRIPT>
window.onerror = null;
function testErrorFunction() {
testErrorFunction();
}
</SCRIPT>
<BODY onload="testErrorFunction()">
test message
</BODY>
Example 3: Error handling function. The function myOnError is defined here, which catches JavaScript errors. This function uses three arrays to store the message, URL, and offending string for each error. If the user clicks the Display Error Report button, the displayErrors function opens a window and generates an error message in it. Note that this function returns true to suppress the standard JavaScript error dialog.
<SCRIPT>
window.onerror = myOnError
msgArray = new Array()
urlArray = new Array()
lnoArray = new Array()
function myOnError(msg, url, lno) {
msgArray[msgArray.length]
= msg
urlArray[urlArray.length] = url
lnoArray[lnoArray.length]
= lno
return true
}
function displayErrors() {
win2=window.open('','window2','scrollbars=yes')
win2.document.writeln('<B>Error Report</B><P>')
for (var i=0; i < msgArray.length; i++) {
win2.document.writeln('<B>Error in file:</B> '
+ urlArray[i] + '<BR>')
win2.document.writeln('<B>Line
number:</B> ' + lnoArray[i] + '<BR>')
win2.document.writeln('<B>Message:</B> '
+ msgArray[i] + '<P>')
}
win2.document.close()
}
</SCRIPT>
<BODY onload="noSuchFunction()">
<FORM>
<BR><INPUT TYPE="button" VALUE="This button has a syntax error" onClick="alert('unterminated string')">
<P><INPUT TYPE="button" VALUE="Display Error Report" onClick="displayErrors()">
</FORM>
This example will give the output:
Error Report Error in file: file:///c%7C/temp/onerror.html Line number: 34 Message: unterminated string literal Error in file: file:///c%7C/temp/onerror.html Line number: 34 Message: missing ) after argument list Error in file: file:///c%7C/temp/onerror.html Line number: 30 Message: noSuchFunction is not defined
Example 4: An event handler calls a function. In the IMG tag, the onError handler calls the badImage function when errors occur while loading the image.
<SCRIPT>
function badImage(theImage) {
alert('Error: ' + theImage.name + ' did not load properly.')
}
</SCRIPT>
<FORM>
<IMG NAME="imageBad2" SRC="orca.gif" ALIGN="left" BORDER="2" onError="badImage(this)">
</FORM>
onfocus
– setting focus on an element. Executes JavaScript code when the focus event occurs; that is, if a window, frame, or set of frames receives focus or if a form element receives focus. The onfocus event occurs when an element receives focus. The onfocus event is often used in input fields. All HTML elements EXCEPT: base, bdo, br, head, html, iframe, meta, param, script, style, и title
Run JavaScript when the input field receives focus:
<input type="text" onfocus="myFunction()">
Here the onFocus handler is used on the valueField Textarea object to call the valueCheck function.
<INPUT TYPE="textarea" VALUE="" NAME="valueField" onFocus="valueCheck()">
onfocusin
The onfocusin event occurs when an element receives focus. The onfocusin event is often used in input fields. All HTML elements EXCEPT: base, bdo, br, head, html, iframe, meta, param, script, style, и title
Run JavaScript when an input field is about to receive focus:
<input type="text" onfocusin="myFunction()">
onfocusout
The onfocusout event occurs when an element loses focus. The onfocusout event is often used in input fields. The onfocusout event is often used during form validation (when the user leaves the form field). All HTML elements EXCEPT: base, bdo, br, head, html, iframe, meta, param, script, style, и title
Run JavaScript when an input field is about to lose focus:
<input type="text" onfocusout="myFunction()">
onfullscreenchange
The fullscreenchange event occurs when an element is viewed in full screen mode. Use the element.requestFullscreen() method to view the element in full screen mode. Use the element.exitFullscreen() method to cancel full screen mode. Each browser requires a specific prefix (see parentheses): 45.0 (webkit), 11.0 (ms), 47.0 (moz), 5.1 (webkit), 15.0 (webkit)
Display some text when viewing a page in full screen mode:
document.addEventListener("fullscreenchange", function() {
output.innerHTML = "fullscreenchange event fired!";
});
Use prefixes for cross-browser code:
/* Стандартный синтаксис */
document.addEventListener("fullscreenchange", function() {
...
});
/* Firefox */
document.addEventListener("mozfullscreenchange", function() {
...
});
/* Chrome, Safari and Opera */
document.addEventListener("webkitfullscreenchange", function() {
...
});
/* IE / Edge */
document.addEventListener("msfullscreenchange", function() {
...
});
onfullscreenerror
The fullscreenerror event occurs when an element cannot be viewed in full screen mode, even though it was requested. Use the element.requestFullscreen() method to view the element in full screen mode. Use element.exitFullscreen() method to cancel full screen mode.
Warning text if the element cannot be viewed in full screen mode:
document.addEventListener("fullscreenerror", function() {
alert("Fullscreen denied")
});
Use prefixes for cross-browser code:
/* Стандартный синтаксис */
document.addEventListener("fullscreenerror", function() {
...
});
/* Firefox */
document.addEventListener("mozfullscreenerror", function() {
...
});
/* Chrome, Safari and Opera */
document.addEventListener("webkitfullscreenerror", function() {
...
});
/* IE / Edge */
document.addEventListener("msfullscreenerror", function() {
...
});
onhashchange
– changing the binding of part of the address. HTML tag support: body. The onhashchange event occurs when changes have been made to the anchor portion (starts with the ‘#’ character) of the current URL. An example of what the anchor part actually is: Let’s say the current URL is http://www.example.com/test.htm#part2 – The anchor part of that URL would be #part2.
To trigger this event you can:
Change the binding part by setting the location.hash or location.href property of the Location object
Go to the current page with another bookmark (use the back or forward buttons)
Click on the bookmark anchor link
Execute JavaScript when part of the binding has changed:
<body onhashchange="myFunction()">
How to assign an “onhashchange” event to a window object:
window.onhashchange = myFunction;
oninput
– start of data entry. The oninput event occurs when the element receives user input. This event occurs when the value of an input or textarea element changes. This event is similar to the onchange event. The difference is that the oninput event occurs immediately after the element’s value changes, while onchange occurs when the element loses focus after its content has changed. Another difference is that the onchange event also works on select elements. HTML tag support: input type=”color”, input type=”date”, input type=”datetime”, input type=”email”, input type=”month”, input type=”number”, input type=”password”, input type=”range”, input type=”search”, input type=”tel”, input type=”text”, input type=”time”, input type=”url”, input type=”week” and textarea
Execute JavaScript when the user writes something in the input field:
<input type="text" oninput="myFunction()">
Range Slider – How to dynamically update the slider value:
<input type="range" oninput="myFunction(this.value)">
oninvalid
– the item is damaged. The oninvalid event occurs when the input element being sent is invalid. For example, an input field is invalid if the required attribute is set and the field is empty (the required attribute specifies that the input field must be filled in before the form can be submitted). HTML tag support: input
Warning about some text if the input field is invalid:
<input type="text" oninvalid="alert('You must fill out the form!');" required>
Warning text if input field contains less than 6 characters:
Имя: <input type="text" id="myInput" name="fname" pattern=".{6,}" required>
<script>
document.getElementById("myInput").addEventListener("invalid", myFunction);
function myFunction() {
alert("Must contain 6 or more characters");
}
</script>
Warning text if the input field contains a number that is less than 2 or greater than 5:
Номер: <input type="number" id="myInput" name="quantity" min="2" max="5" required>
<script>
document.getElementById("myInput").addEventListener("invalid", myFunction);
function myFunction() {
alert("You must choose a number from 2 to 5. You have chosen: " + this.value);
}
</script>
onkeydown
– key pressed. The onkeydown event occurs when the user presses a key (on the keyboard). The order of events associated with the onkeydown event is: onkeydown, onkeypress, onkeyup. All HTML elements EXCEPT: base, bdo, br, head, html, iframe, meta, param, script, style, и title. The KeyDown event always occurs before the KeyPress event. If onKeyDown returns false, the KeyPress event is not raised. This prevents KeyPress events from occurring when the user holds down a key.
type – Indicates the event type.
target – Indicates the object to which the event was originally sent.
layerX, layerY, pageX, pageY, screenX, screenY – For an over-window event, represents the location of the cursor at the time the event occurred. For an event on top of a form, represents the position of the form element.
which – ASCII-the value of the key pressed. To get the actual letter, number, or character of the key pressed, use the String.fromCharCode method. To set this property when the ASCII value is unknown, use the String.charCodeAt.
modifiers – Contains a list of modifier keys pressed when the event occurs.
Run JavaScript when the user presses a key:
<input type="text" onkeydown="myFunction()">
Use “onkeydown” with event “onkeyup”:
<input type="text" onkeydown="keydownFunction()" onkeyup="keyupFunction()">
Here the blockA function is used to calculate the characters entered from the keyboard into the textentry text box. If the user enters “a” or “A”, the function returns false and the text box does not display a value. In this function, the which property of the event assigns the ASCII value of the user’s key pressed to the keyChar variable. The if statement evaluates keyChar and returns false for the specified characters:
<form name="main">
<input name="textentry"
type=text size=10 maxlength=10>
</form>
<script>
function blockA(e) {
var keyChar = String.fromCharCode(e.which);
if (keyChar == 'A' || keyChar == 'a')
return false;
}
document.main.textentry.onkeydown = blockA;
</script>
onkeypress
– a key is pressed and then released. Executes JavaScript code when the KeyPress event occurs; that is, if the user holds down the key. The onkeypress event occurs when the user presses a key (on the keyboard). The onkeypress event does not fire for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers. To detect only whether the user pressed a key, use the onkeydown event instead because it works for all keys. The order of events associated with the onkeydown event is: onkeydown, onkeypress, onkeyup. All HTML elements EXCEPT: base, bdo, br, head, html, iframe, meta, param, script, style, и title. The KeyPress event fires immediately after the KeyDown event only when onKeyDown returns something other than false. The KeyPress event occurs repeatedly until the user releases the key. You can cancel individual KeyPress events.
type – Indicates the event type.
target – Indicates the object to which the event was originally sent.
layerX, layerY, pageX, pageY, screenX, screenY – For an event, the overlay represents the location of the cursor at the time the event occurred. For an over-form event, represents the position of a form element.
which – ASCII-the value of the key pressed. To get the actual letter, number, or character of the key pressed, use the String.fromCharCode method. To set this property when the ASCII value is unknown, use the String.charCodeAt.
modifiers – Contains a list of modifier keys pressed when the event occurs.
Run JavaScript when the user presses a key:
<input type="text" onkeypress="myFunction()">
Here, the captureEvents method captures keyboard input, and the onKeyPress handler calls the blockA function to check for keypresses. If the “a” or “z” keys are pressed, the function scrolls the Navigator window.
function blockA(e) {
var keyChar = String.fromCharCode(e.which);
if (keyChar == 'A' || keyChar == 'a')
self.scrollBy(10,10);
else if(keyChar == 'Z' || keyChar == 'z')
self.scrollBy(-10,-10);
else return false;
}
document.captureEvents(Event.KEYPRESS);
document.onkeypress = blockA;
onkeyup
– key released. The onkeyup event occurs when the user releases a key (on the keyboard). The order of events associated with the onkeydown event is: onkeydown, onkeypress, onkeyup. All HTML elements EXCEPT: base, bdo, br, head, html, iframe, meta, param, script, style, and title.
type – Indicates the event type.
target – Indicates the object to which the event was originally sent.
layerX, layerY, pageX, pageY, screenX, screenY – For an event, the overlay represents the location of the cursor at the time the event occurred. For an over-form event, represents the position of a form element.
which – ASCII-the value of the key pressed. To get the actual letter, number, or character of the key pressed, use the String.fromCharCode method. To set this property when the ASCII value is unknown, use the String.charCodeAt.
modifiers – Contains a list of modifier keys pressed when the event occurs.
Run JavaScript when the user releases the key:
<input type="text" onkeyup="myFunction()">
Use “onkeydown” with the “onkeyup” event:
<input type="text" onkeydown="keydownFunction()" onkeyup="keyupFunction()">
Output the actual key that was issued inside the text field:
Введите свое имя: <input type="text" id="fname" onkeyup="myFunction()">
<script>
function myFunction() {
var x = document.getElementById("fname").value;
document.getElementById("demo").innerHTML = x;
}
</script>
Here, the captureEvents method captures keyboard input, and the onKeyUp handler calls the Key_Up function. The function’s alert method opens a dialog box to display the value of the key pressed:
function Key_Up(e) {
var keyChar = String.fromCharCode(e.which);
alert("Hold '" + keyChar +"' again for me, okay?");
}
document.onkeyup=Key_Up;
document.captureEvents(Event.KEYUP);
onload
– item loaded. The onload event occurs when an object has been loaded. The onload event is most often used on the body element to execute a script after the web page has fully loaded all of its content (including images, script files, CSS files, etc.). The onload event can be used to check the visitor’s browser type and browser version and load the appropriate version of the web page based on the information received. The onload event can also be used to handle cookies.
The onLoad handler is used in the BODY or FRAMESET tag, for example, BODY onLoad=”…”. For FRAMESET and FRAME tags: the onLoad handler event in the frame (placed in the BODY tag) occurs before the onLoad of the FRAMESET tag (placed in the FRAMESET tag). For images, the onLoad handler specifies the script to be executed when the image is output. Don’t confuse image output with image upload. You can load multiple images, then display them one at a time in the same Image object by setting the object’s src property. If you change the image output this way, onLoad is executed every time the image is output, not just when the images are loaded into memory.
If you specify an onLoad handler for an Image object that outputs a looping GIF (multi-image GIF), each animation loop includes an onLoad handler, and the handler is executed once for each loop. You can use the onLoad handler to create a JavaScript animation by repeatedly setting the src property of the Image object.
type – Indicates the event type.
target – Indicates the object to which the event was originally sent.
width, height – For an event on top of a window, but not on top of a layer, these properties represent the window’s width and height.
Run JavaScript immediately after page loads:
<body onload="myFunction()">
In JavaScript, use the method addEventListener():
object.addEventListener("load", myScript);
Display a message when the page loads. Here the onLoad handler prints a greeting after the page has loaded.
<BODY onLoad="window.alert("Welcome to the Brave New World home page!")>
Display a message when loading an image. Here two Image objects are created: one by the Image constructor, and the second by the IMG tag. Each Image object has an onLoad handler that calls the displayAlert function, which displays a message. For an image created by an IMG tag, the alert dialog displays the name of the image. For an image created by the Image constructor, alert displays a message without the image name. This occurs because the onLoad handler for the object created by the Image constructor must be the name of a function and it cannot specify parameters for the displayAlert function.
<SCRIPT>
imageA = new Image(50,50)
imageA.onload=displayAlert
imageA.src="cyanball.gif"
function displayAlert(theImage) {
if (theImage==null) {
alert('An image loaded')
}
else alert(theImage.name + ' has been loaded.')
}
</SCRIPT>
<IMG NAME="imageB" SRC="greenball.gif" ALIGN="top" onLoad=displayAlert(this)><BR>
Looping GIF animation output. The image displayed here is birdie.gif, which is an animated GIF image. The onLoad handler increments the cycles variable, which tracks the number of animation cycles. To see the value of cycles, the user clicks the Count Loops button.
<SCRIPT>
var cycles=0
</SCRIPT>
<IMG ALIGN="top" SRC="birdie.gif" BORDER=0 onLoad="++cycles">
<INPUT TYPE="button" VALUE="Count Loops" onClick="alert('The animation has looped ' + cycles + ' times.')">
Change the GIF animation displayed. This example uses the onLoad handler to rotate six GIF animations. Each animation is shown as a sequence of individual Image objects. When the document is loaded, !anim0.html is output. When this animation completes, the onLoad handler causes the next file, !anim1.html, to be loaded instead of the first file. After the last animation, !anim5.html, completes, the first file is displayed again. Note that the changeAnimation function does not call itself after changing the src property of the Image object. This happens because the src property is changed, the image’s onLoad handler is enabled, and the changeAnimation function is called.
<SCRIPT>
var whichImage=0
var maxImages=5
function changeAnimation(theImage) {
++whichImage
if (whichImage <= maxImages) {
var imageName="!anim" + whichImage + ".gif"
theImage.src=imageName
} else {
whichImage=-1
return
}
}
</SCRIPT>
<IMG NAME="changingAnimation" SRC="!anim0.gif" BORDER=0 ALIGN="top" onLoad="changeAnimation(this)">
Use the onload event for the img element. “Image Loaded” notification immediately after the image is loaded:
<img src="javascriptw3.gif" onload="loadImage()" width="100" height="132">
<script>
function loadImage() {
alert("Image is loaded");
}
</script>
Use onload event to handle cookies:
<body onload="checkCookies()">
<script>
function checkCookies() {
var text = "";
if (navigator.cookieEnabled == true) {
text = "Cookies enabled.";
} else {
text = "Cookies are not enabled.";
}
document.getElementById("demo").innerHTML = text;
}
</script>
onloadeddata
– file data loaded. Handler for the loadeddata event, which occurs when the audio/video can already be played at the current position, but media data continues to be loaded. The onloadeddata event occurs when the media frame is loaded, but does not guarantee that enough data is available to begin playback. The onloadeddata event occurs after onloadedmetadata and before oncanplay.
When loading media, 7 events occur in the following order:
1. onloadstart
2. ondurationchange
3. onloadedmetadata
4. onloadeddata
5. onprogress
6. oncanplay
7. oncanplaythrough
Execute JavaScript when data is available for the current frame (for video):
<video onloadeddata="myFunction()">
Execute JavaScript when data is available for the current frame (for audio):
<audio onloadeddata="myFunction()">
onloadedmetadata
– file metadata loaded. Handler for the loadedmetadata event, which occurs when metadata (duration, frame dimensions (for video) and track text) for the specified audio/video file has been loaded. The onloadedmetadata event occurs when metadata for the media has been loaded.
Metadata for audio or video consists of:
Duration
Dimensions (video)
Tracks
Run JavaScript when loading video metadata:
<video onloadedmetadata="myFunction()">
В JavaScript:
object.onloadedmetadata = function(){myScript};
In JavaScript, use the method addEventListener():
object.addEventListener("loadedmetadata", myScript);
onloadstart
– start loading the element. Handler for the loadstart event, which occurs when the process of loading an audio/video file begins.
onmessage
– message appears. The onmessage event occurs when a message is received through an event source. The event object for the onmessage event supports the following properties:
data – Contains the actual message
origin — URL of the document that raised the event.
LastEventId — ID of the last message seen in the event stream.
Related events:
onopen – occurs when a connection to the server is open.
onerror – Occurs when a problem occurs
Create a new EventSource object and specify the URL of the page that sends the updates. Every time an update is received, the onmessage event occurs. When the onmessage event occurs, place the received data in a div element with id=”myDIV”:
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("myDIV").innerHTML += event.data + "<br>";
};
onmousedown
– mouse button is pressed. Handler for the mousedown event, which occurs when the left mouse button is pressed. The difference with the click event is that click is a combination of the mousedown and mouseup events. Executes JavaScript code when the MouseDown event occurs; that is, when the user presses a mouse key. If onMouseDown returns false, the default action (entering drag mode, entering selection mode, or activating a hyperlink) is canceled. Activation is triggered by the MouseDown event on the hyperlink. If the link is activated, it changes color to indicate the new state. Default action varies: initiate drag, text selection, scroll or zoom (combined with wheel press when supported)
The onmousedown event occurs when the user presses the mouse button over an HTML element. Order of events for left and middle mouse button:
onmousedown
onmouseup
on click
Order of events for the right mouse button:
onmousedown
onmouseup
oncontextmenu
type – Indicates the event type.
target – Indicates the object to which the event was originally sent.
layerX, layerY, pageX, pageY, screenX, screenY- The location of the cursor when the MouseDown event occurs.
which – Represents 1 for a left mouse click and 3 for a right mouse click.
modifiers – Contains a list of modifier keys pressed when the MouseDown event occurred.
Call a function when the mouse button is pressed over a paragraph:
<p onmousedown="myFunction()">Click the text!</p>
Here the user can move the image on the HTML page by dragging it with the mouse. Your HTML code defines an image and positions it in a layer called container1. In the JavaScript code, event handlers set the positioning properties of container1 when the user drags the image, creating an animation. The ID attribute of the P element that contains the image is set to container1, making container1 a unique identifier for the paragraph and the image. The STYLE tag creates a layer for container1 and positions it. The JavaScript code below defines the onMouseDown, onMouseUp, and onMouseMove handlers. Using style sheets, the image is initially defined and positioned like this:
<HEAD>
<STYLE type="text/css">
#container1 {
position:absolute; left:200; top:200}
</STYLE>
</HEAD>
<BODY>
<P ID="container1">
<img src="backgrnd.gif" name="myImage" width=96 height=96>
</P>
</BODY>
In this code, the captureEvents method captures the MouseUp and MouseDown events. The DRAG_begindrag and DRAG_enddrag functions are called respectively to handle these events. If the user presses the left mouse button, the DRAG_begindrag function starts, capturing MouseMove events and telling the DRAG_drag function to handle them. It then assigns the value of the pageX property of the MouseDown event to the DRAG_lastX property, the value of the pageY property to the DRAG_lastY property, and true to the DRAG_dragging property. The DRAG_drag function evaluates DRAG_dragging to ensure that the MouseMove event was captured by the DRAG_begindrag function, then uses the moveBy method to position the object and assigns values to the DRAG_lastX and DRAG_lastY properties. When the user releases the left mouse button, the DRAG_enddrag function stops capturing MouseMove events. DRAG_enddrag then ensures that no other functions are called by setting onmousemove to Null and DRAG_dragging to false.
<SCRIPT>
container1.captureEvents(Event.MOUSEUP|Event.MOUSEDOWN);
container1.onmousedown=DRAG_begindrag;
container1.onmouseup=DRAG_enddrag;
var DRAG_lastX, DRAG_lastY, DRAG_dragging;
function DRAG_begindrag(e) {
if (e.which == 1) {
window.captureEvents(Event.MOUSEMOVE);
window.onmousemove=DRAG_drag;
DRAG_lastX=e.pageX;
DRAG_lastY=e.pageY;
DRAG_dragging=true;
return false;
}
else {
/*Here's some work on handling right mouse clicks*/
return true;
}
}
function DRAG_enddrag(e) {
if (e.which == 1) {
window.releaseEvents(Event.MOUSEMOVE);
window.onmousemove=null
DRAG_dragging=false;
return false;
}
else {
/*Here's some work on handling right mouse clicks*/
return true;
}
}
function DRAG_drag(e) {
if (DRAG_dragging) {
/*This function is only called if MOUSEMOVE is captured*/
moveBy(e.pageX-DRAG_lastX, e.pageY-DRAG_lastY);
DRAG_lastX = e.pageX;
DRAG_lastY = e.pageY;
return false;
}
else {
return true;
}
}
</SCRIPT>
onmouseenter
– The mouse pointer is over an element. A handler for the mouseenter event, which occurs when the mouse cursor enters the element’s area. Unlike mouseover, the mouseenter event does not bubble (“bubble”), that is, it does not occur if the mouse cursor hits a child element of the specified element. The onmouseenter event occurs when the mouse pointer enters an element. The onmouseenter event is often used in conjunction with the onmouseleave event, which occurs when the mouse pointer leaves an element. The onmouseenter event is similar to the onmouseover event. The difference is that the onmouseenter event does not bubble up (does not propagate up the document hierarchy).
One mouseenter event is sent to each element of the hierarchy as they enter. Here 4 events are sent to the four elements of the hierarchy when the pointer reaches the text. A single mouseover event is sent to the deepest element of the DOM tree, then it bubbles up in the hierarchy until it is canceled by a handler or reaches the root. When there is a deep hierarchy, the number of mouseover events sent can be quite large and cause significant performance issues. In such cases, it is better to handle mouseenter events. When combined with the corresponding mouseleave event (which fires on an element when the mouse leaves the content area), the mouseenter event acts very similar to the CSS pseudo-class :hover.
Call a function when you hover over an image:
<img onmouseenter="bigImg(this)" src="smiley.gif" alt="Smiley">
JavaScript:
object.onmouseenter = function(){myScript};
JavaScript, using the addEventListener() method:
object.addEventListener("mouseenter", myScript);
This example demonstrates the difference between the onmousemove, onmouseenter and mouseover events:
<div onmousemove="myMoveFunction()"> <p id="demo1">I will demonstrate onmousemove!</p> </div> <div onmouseenter="myEnterFunction()"> <p id="demo2">I will demonstrate onmouseenter!</p> </div> <div onmouseover="myOverFunction()"> <p id="demo3">I will demonstrate onmouseover!</p> </div>
The following trivial example uses the mouseenter event to change the border of a div element when the mouse enters its allocated space. It then adds an element to the list with event number mouseenter or mouseleave.
<SCRIPT>
var enterEventCount = 0;
var leaveEventCount = 0;
const mouseTarget = document.getElementById("mouseTarget");
const unorderedList = document.getElementById("unorderedList");
mouseTarget.addEventListener("mouseenter", (e) => {
mouseTarget.style.border = "5px dotted orange";
enterEventCount++;
addListItem("This is mouseenter event " + enterEventCount + ".");
});
mouseTarget.addEventListener("mouseleave", (e) => {
mouseTarget.style.border = "1px solid #333";
leaveEventCount++;
addListItem("This is mouseleave event " + leaveEventCount + ".");
});
function addListItem(text) {
// Create a new text node using the provided text
var newTextNode = document.createTextNode(text);
// Create a new li element
var newListItem = document.createElement("li");
// Add a text node to the li element
newListItem.appendChild(newTextNode);
// Add the newly created list item to the list
unorderedList.appendChild(newListItem);
}
<SCRIPT>
<style>
#mouseTarget {
box-sizing: border-box;
width: 15rem;
border: 1px solid #333;
}
</style>
<div id="mouseTarget">
<ul id="unorderedList">
<li>No events yet!</li>
</ul>
</div>
onmouseleave
– the mouse pointer has left the element. A handler for the mouseleave event, which occurs when the mouse cursor leaves the element’s area. Unlike mouseout, the mouseenter event does not bubble (“bubble”), that is, it does not occur if the mouse cursor hits a child element of the specified element. The onmouseleave event occurs when the mouse pointer leaves the element. The onmouseleave event is often used in conjunction with the onmouseenter event, which occurs when the mouse pointer enters an element. The onmouseleave event is similar to the onmouseout event. The difference is that the onmouseleave event does not bubble up (does not propagate up the document hierarchy).
The mouseleave event fires when the cursor of a manipulator (usually a mouse) moves outside the bounds of an element. mouseleave and mouseout are similar, but differ in that mouseleave does not pop up, while mouseout does. This means that mouseleave fires when the cursor leaves the bounds of an element and all of its children, while mouseout fires when the cursor leaves the bounds of an element or one of its children (even if the cursor is still within the element).
Call a function when the mouse pointer moves outside the image:
<img onmouseleave="normalImg(this)" src="smiley.gif" alt="Smiley">
JavaScript:
object.onmouseleave = function(){myScript};
JavaScript, using the addEventListener() method:
object.addEventListener("mouseleave", myScript);
This example demonstrates the difference between the onmousemove, onmouseleave and onmouseout events:
<div onmousemove="myMoveFunction()"> <p id="demo1">I will demonstrate onmousemove!</p> </div> <div onmouseleave="myLeaveFunction()"> <p id="demo2">I will demonstrate onmouseleave!</p> </div> <div onmouseout="myOutFunction()"> <p id="demo3">I will demonstrate onmouseout!</p> </div>
The mouseout documentation has an example illustrating the difference between mouseout and mouseleave. The following example shows how to use mouseout to simulate the delegation principle of the mouseleave event.
<ul id="test">
<li>
<ul class="leave-sensitive">
<li>item 1-1</li>
<li>item 1-2</li>
</ul>
</li>
<li>
<ul class="leave-sensitive">
<li>item 2-1</li>
<li>item 2-2</li>
</ul>
</li>
</ul>
<script>
var delegationSelector = ".leave-sensitive";
document.getElementById("test").addEventListener(
"mouseout",
function (event) {
var target = event.target,
related = event.relatedTarget,
match;
// search for a parent node matching the delegation selector
while (
target &&
target != document &&
!(match = matches(target, delegationSelector))
) {
target = target.parentNode;
}
// exit if no matching node has been found
if (!match) {
return;
}
// loop through the parent of the related target to make sure that it's not a child of the target
while (related && related != target && related != document) {
related = related.parentNode;
}
// exit if this is the case
if (related == target) {
return;
}
// the "delegated mouseleave" handler can now be executed
// change the color of the text
target.style.color = "orange";
// reset the color after a small amount of time
setTimeout(function () {
target.style.color = "";
}, 500);
},
false,
);
// function used to check if a DOM element matches a given selector
// the following code can be replaced by this IE8 compatible function: https://gist.github.com/2851541
function matches(elem, selector) {
// the matchesSelector is prefixed in most (if not all) browsers
return elem.matchesSelector(selector);
}
</script>
onmousemove
– The mouse pointer is moved over the element. Handler for the mousemove event, which occurs when the mouse pointer moves over an element.
type – Indicates the event type.
target – Indicates the object to which the event was originally sent.
layerX, layerY, pageX, pageY, screenX, screenY – The location of the cursor at the moment the MouseMove event occurs.
JavaScript:
object.onmousemove = function(){myScript};
JavaScript, using the addEventListener() method:
object.addEventListener("mousemove", myScript);
Call a function when you hover over a div element:
<div onmousemove="myFunction()">Move the cursor over me</div>
The following example uses the mousedown, mousemove, and mouseup events to allow the user to draw on the HTML canvas. Its functionality is simple: the line thickness is set to 1 and the color is always black. When the page loads, the constants myPics and context are created to store a reference to the canvas and 2D context that we will use for drawing. Drawing begins when the mousedown event fires. We first store the x and y coordinates of the mouse pointer in x and y variables and then set isDrawing to true. When the mouse pointer moves across the page, the mousemove event is fired. If isDrawing is true, the event handler calls the drawLine function to draw a line from the stored x and y values to the current location. When the drawLine() function returns, we adjust the coordinates and then store them in x and y coordinates. The mouseup event draws the last line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false.
<script>
// When true, moving the mouse draws on the canvas
let isDrawing = false;
let x = 0;
let y = 0;
const myPics = document.getElementById("myPics");
const context = myPics.getContext("2d");
// event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas.
// Add the event listeners for mousedown, mousemove, and mouseup
myPics.addEventListener("mousedown", (e) => {
x = e.offsetX;
y = e.offsetY;
isDrawing = true;
});
myPics.addEventListener("mousemove", (e) => {
if (isDrawing) {
drawLine(context, x, y, e.offsetX, e.offsetY);
x = e.offsetX;
y = e.offsetY;
}
});
window.addEventListener("mouseup", (e) => {
if (isDrawing) {
drawLine(context, x, y, e.offsetX, e.offsetY);
x = 0;
y = 0;
isDrawing = false;
}
});
function drawLine(context, x1, y1, x2, y2) {
context.beginPath();
context.strokeStyle = "black";
context.lineWidth = 1;
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.stroke();
context.closePath();
}
</script>
<style>
canvas {
border: 1px solid black;
width: 560px;
height: 360px;
}
</style>
<h1>Drawing with mouse events</h1>
<canvas id="myPics" width="560" height="360"></canvas>
onmouseout
– the mouse pointer moves out of the element. A handler for the mouseout event, which occurs when the mouse pointer moves outside the bounds of an element. Executes JavaScript code when the MouseOut event occurs; that is, each time the mouse pointer leaves the area (in the client image map) or hyperlink. If the mouse pointer moves from one area of the client image map to another, you will first receive onMouseOut for the first area, and then onMouseOver for the second area. Area tags that use onMouseOut are required to have an HREF attribute in the AREA tag. You must return true in the event handler if you want to set the status or defaultStatus properties using onMouseOver.
The onmouseout event occurs when the mouse pointer moves outside of an element. The onmouseout event is often used in conjunction with the onmouseover event, which occurs when you hover over an element. The onmouseout event is similar to the onmouseleave event. The difference is that the onmouseleave event does not bubble up (does not propagate up the document hierarchy).
type – Indicates the event type.
target – Indicates the object to which the event was originally sent.
layerX, layerY, pageX, pageY, screenX, screenY – The location of the cursor at the moment the MouseOut event occurs
Call a function when the mouse pointer moves outside the image:
<img onmouseout="normalImg(this)" src="smiley.gif" alt="Smiley">
The following example illustrates the difference between the mouseout and mouseleave events. The mouseleave event is added to the ul to color the list purple whenever the mouse leaves the ul. mouseout is added to the list to color the target element orange when the mouse leaves it. When you try this you will find that mouseout is sent to individual list items and mouseleave is sent to the entire list, thanks to the element hierarchy and the fact that list items hide the base ul.
<script>
const test = document.getElementById("test");
// Briefly make the list purple when the mouse moves off the
// <ul> element
test.addEventListener(
"mouseleave",
(event) => {
// highlight the mouseleave target
event.target.style.color = "purple";
// reset the color after a short delay
setTimeout(() => {
event.target.style.color = "";
}, 1000);
},
false,
);
// Briefly make an <li> orange when the mouse moves off of it
test.addEventListener(
"mouseout",
(event) => {
// highlight the mouseout target
event.target.style.color = "orange";
// reset the color after a short delay
setTimeout(() => {
event.target.style.color = "";
}, 500);
},
false,
);
</script>
<ul id="test">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
onmouseover
– The mouse pointer moves over the element. A handler for the mouseover event, which occurs when the mouse cursor is hovered over an element. The onmouseover event occurs when the mouse pointer enters an element. The onmouseover event is often used in conjunction with the onmouseout event, which occurs when the mouse pointer leaves an element. The onmouseover event is similar to the onmouseenter event. The difference is that the onmouseenter event does not bubble up (does not propagate up the document hierarchy). The mouseover event is raised on an element when a pointing device (such as a mouse or trackpad) is used to move the cursor over the element or one of its children.
Call a function when you hover over an image:
<img onmouseover="bigImg(this)" src="smiley.gif" alt="Smiley">
By default, the HREF value of an anchor is displayed in the status bar at the bottom of the browser when the user hovers the mouse over the anchor. In the following example, onMouseOver displays a special message “Click this if you dare.”
<A HREF="http://home.netscape.com/" onMouseOver="window.status='Click this if you dare!'; return true">Click me</A>
onmouseup
– the mouse button is released over the element. A handler for the mouseup event, which occurs when the mouse button on an element is released. If onMouseUp returns false, the default promotion is cancelled. For example, if onMouseUp returns false when a hyperlink is active, the link is not included. So, if MouseUp occurs when the hyperlink is inactive (perhaps in the case where onMouseDown returns false), the link is not included. Activation is caused by the MouseDown event on the link. If the link is active, it changes color to reflect the new state. The onmouseup event occurs when the mouse button is released over an element.
The mouseup event is raised on an element when a button on a pointing device (such as a mouse or trackpad) is released while the pointer is inside it. Mouseup events are the opposite of mousedown events.
Order of events for the left and middle mouse buttons:
onmousedown
onmouseup
on click
Order of events for the right mouse button:
onmousedown
onmouseup
oncontextmenu
type – Indicates the event type.
target – Indicates the object to which the event was originally sent.
layerX, layerY, pageX, pageY, screenX, screenY – The location of the cursor at the moment the MouseUp event occurs.
which – Represents 1 for the left key and 3 for the right mouse key.
modifiers – Contains a list of modifier keys pressed when the MouseUp event occurred.
Call a function when the mouse button is released over a paragraph:
<p onmouseup="mouseUp()">Click the text!</p>
onmousewheel (onwheel)
– the mouse wheel is used. A handler for the wheel event, which occurs when the mouse wheel is scrolled forward or backward on an element. The onwheel event occurs when the mouse wheel is hovered over an element. The onwheel event also occurs when the user scrolls the page using the touchpad. This event replaces the non-standard deprecated mouse wheel event. Don’t confuse the wheel event with the scroll event. The wheel event does not necessarily dispatch a scroll event. For example, the element may not be scrollable at all. Zoom actions using the wheel or trackpad also trigger wheel events. The scroll event is not necessarily fired by the wheel event. Elements can also be scrolled using the keyboard, dragging the scroll bar, or using JavaScript.
Even if the wheel event triggers scrolling, the delta* values in the wheel event do not necessarily reflect the direction in which the content is scrolling. Therefore, do not rely on the delta* properties of the wheel event to get the scroll direction. Instead, detect changes in the target’s ScrollLeft and ScrollTop values in the scroll event.
The Wheel event can be canceled. If the event is canceled, no scrolling or zooming occurs. This can cause performance issues because the browser has to wait for each wheel event to be processed before actually scrolling the content. This can be avoided by setting passive: true when calling addEventListener(), which may cause the browser to generate non-cancellable wheel events.
When the user scrolls the mouse wheel over a div element, change its font size:
document.getElementById("myDIV").addEventListener("wheel", myFunction);
function myFunction() {
this.style.fontSize = "35px";
}
This example shows how to scale an element using the mouse wheel (or other pointing device).
<script>
function zoom(event) {
event.preventDefault();
scale += event.deltaY * -0.01;
// Restrict scale
scale = Math.min(Math.max(0.125, scale), 4);
// Apply scale transform
el.style.transform = `scale(${scale})`;
}
let scale = 1;
const el = document.querySelector("div");
el.onwheel = zoom;
</script>
<style>
body {
min-height: 100vh;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
}
div {
width: 105px;
height: 105px;
background: #cdf;
padding: 5px;
}
</style>
<div>Scale me with your mouse wheel.</div>
onoffline
– the browser is running in offline mode. The onoffline event occurs when the browser goes offline. The onoffline event is the opposite of the ononline event.
Call the function when the browser goes offline:
<body onoffline="myFunction()">
ononline
– the browser is launched in online mode. The ononline event occurs when the browser starts going online. An online event is the opposite of an onoffline event.
Call the function when the browser starts online:
<body ononline="myFunction()">
onpagehide
– the user navigates away from the page. The onpagehide event occurs when the user leaves a web page. There are several ways to navigate away from a page. For example. by clicking on a link, refreshing the page, submitting a form, closing the browser window, etc. The onpagehide event is sometimes used instead of the onunload event because the onunload event causes the page to not be cached. To find out whether a page is loaded directly from the server or is cached, you can use the persisted property of the PageTransitionEvent object. This property returns true if the page is cached by the browser, false otherwise.
Call the function when the user navigates away from the web page:
<body onpagehide="myFunction()">
onpageshow
– the user navigates to the page. The onpageshow event occurs when the user navigates to a web page. The onpageshow event is similar to the onload event, except that it occurs after the onload event when the page is first loaded. Additionally, the onpageshow event occurs every time the page is loaded, whereas the onload event does not occur when the page is loaded from the cache. To find out whether a page is loaded directly from the server or is cached, you can use the persisted property of the PageTransitionEvent object. This property returns true if the page is cached by the browser, false otherwise
Call the function when the user navigates to the web page:
<body onpageshow="myFunction()">
onpaste
– Content has been inserted. The onpaste event occurs when the user pastes some content into an element. The onpaste event is most often used for input elements with type=”text”. The Clipboard API paste event is fired when the user initiates a “paste” action through the browser UI. If the cursor is in an editable context (for example, a textarea or an element with the contenteditable attribute set to true), then the default action is to paste the contents of the clipboard into the document at the cursor position. A handler for this event can access the contents of the clipboard by calling the getData() method on the clipboardData property of the event. To override the default behavior (for example, to paste different data or convert the contents of the clipboard), the event handler must override the default action using event.preventDefault() and then manually insert the desired data. You can create and dispatch a synthetic insert event, but this will not affect the content of the document. This event pops up, can be canceled and is composed. Used only for input fields.
Call the function when text is inserted into an input element:
<input type="text" onpaste="myFunction()" value="Paste something here">
Call the function when text is inserted into the p element. (Note that contenteditable is set to “true”):
<p contenteditable="true" onpaste="myFunction()">Try to paste something inside this paragraph.</p>
Example
<script>
const target = document.querySelector("div.target");
target.addEventListener("paste", (event) => {
event.preventDefault();
let paste = (event.clipboardData || window.clipboardData).getData("text");
paste = paste.toUpperCase();
const selection = window.getSelection();
if (!selection.rangeCount) return;
selection.deleteFromDocument();
selection.getRangeAt(0).insertNode(document.createTextNode(paste));
selection.collapseToEnd();
});
<script>
<div class="source" contenteditable="true">Copy text from this box.</div>
<div class="target" contenteditable="true">And paste it into this one.</div>
onpause
– pause playback. A handler for the pause event, which occurs when audio/video playback is paused by the user or software. The onpause event occurs when the audio/video is paused. The onpause event also occurs when the audio/video has reached the end.
Call a function when the video has been paused:
<video onpause="myFunction()">
onplay
– start playback. Handler for the play event, which occurs when playback of an audio/video file has been started.
Call the function when the video starts playing:
<video onplay="myFunction()">
onplaying
– file playback. Handler for the playing event, which occurs when playback of an audio/video file has started. The onplaying event occurs when audio/video playback begins. The onplaying event also occurs when audio/video resumes after being paused or buffered.
Call a function when the video starts:
<video onplaying="myFunction()">
onprogress
– getting file metadata. A handler for the progress event, which occurs when the specified audio/video file is downloaded from the server. The onprogress event occurs when the browser loads audio or video.
Call a function when loading a video:
<video onprogress="myFunction()">
onratechange
– change playback speed. A handler for the ratechange event, which occurs when the audio/video playback speed changes (for example, when the user switches to slow or fast playback mode). The onratechange event occurs when the media playback speed changes (for example, when the user switches to slow-motion or fast-motion playback mode). This event is raised by the playbackRate property of the Audio/Video object, which sets or returns the current playback speed of the audio/video.
Call a function when the video playback speed changes:
<video onratechange="myFunction()">
onreset
– Data reset completed. Handler for the reset event, which occurs when the form is cleared when the Reset button is clicked. Executes JavaScript code when the reset event occurs; that is, when the user restores the values of form elements (by clicking the Reset button).
Call a function when the form is reset:
<form onreset="myFunction()"> Enter name: <input type="text"> <input type="reset"> </form>
The following example outputs a Text object with a default value of “CA” and a reset button. If the user enters the state abbreviation into the Text object and clicks the reset button, the original value of “CA” is restored. The form’s onReset handler displays a message indicating that the default values have been restored.
<FORM NAME="form1" onReset="alert('Defaults have been restored.')">
State:
<INPUT TYPE="text" NAME="state" VALUE="CA" SIZE="2"><P>
<INPUT TYPE="reset" VALUE="Clear Form" NAME="reset1">
</FORM>
onresize
– resizing an element. Executes JavaScript code when the resize event occurs; that is, when the user or script has changed the size of the window or frame. The onresize event occurs when the browser window has been resized. Tip: To get the size of an element, use the properties clientWidth, clientHeight, InnerWidth, InnerHeight, OuterWidth, OuterHeight, OffsetWidth and/or OffsetHeight. This handler is sent after the HTML has finished rendering with the new inner window sizes. This allows elements and named anchors to be positioned so that they have their requested final size and location, image SRC properties can be restored dynamically, etc.
Call the function when the browser window is resized:
<body onresize="myFunction()">
Using the addEventListener() method to attach a “resize” event to a window object.
window.addEventListener("resize", myFunction);
Here the open_now function creates the myWin window and captures the Resize events. The onResize handler calls the alert_me function, which displays a message if the user resizes the myWin window.
function open_now(){
var myWin;
myWin=window.open("","displayWin","width=400,height=300,resizable=yes,
menubar=no,location=no,alwaysRaised=yes");
var text="<html><head><title>Test</title></head>"
+"<body bgcolor=white><h1>Please resize me</h1></body>"
+"</html>";
myWin.document.write(text);
myWin.captureEvents(Event.RESIZE);
myWin.onresize=alert_me;
}
function alert_me(){
alert("You resized me! \nNow my outer width: " + this.outerWidth +
"\n and my outer height: " +this.outerHeight);
this.focus();
}
onscroll
– Scrolling the element’s contents. The onscroll event occurs when an element’s scrollbar is scrolled. Tip: Use the CSS overflow style property to create a scrollbar for an element. The scroll event fires when the element is scrolled. To determine when scrolling has completed, look at the element’s scroll event.
Call a function when the div is scrolled:
<div onscroll="myFunction()">
Switch between class names at different scroll positions. When the user scrolls down 50 pixels from the top of the page, the class name “test” is added to the element (and removed when scrolling up again).
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.getElementById("myP").className = "test";
} else {
document.getElementById("myP").className = "";
}
}
Insert an element when the user has scrolled down 350px (add a slideUp class):
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350) {
document.getElementById("myImg").className = "slideUp";
}
}
The following example shows how to use the scroll event to detect when the user scrolls an element:
<script>
const element = document.querySelector("div#scroll-box");
const output = document.querySelector("p#output");
element.addEventListener("scroll", (event) => {
output.textContent = "Scroll event fired!";
setTimeout(() => {
output.textContent = "Waiting on scroll events...";
}, 1000);
});
</script>
<div id="scroll-box" style="overflow: scroll; height: 100px; width: 100px; float: left;">
<p style="height: 200px; width: 200px;">Scroll me!</p>
</div>
<p style="text-align: center;" id="output">Waiting on scroll events...</p>
The following example shows how to use the onscroll event handler property to detect when the user scrolls:
<script>
const element = document.querySelector("div#scroll-box");
const output = document.querySelector("p#output");
element.onscroll = (event) => {
output.textContent = "Element scroll event fired!";
setTimeout(() => {
output.textContent = "Waiting on scroll events...";
}, 1000);
};
</script>
<div id="scroll-box" style="overflow: scroll; height: 100px; width: 100px; float: left;">
<p style="height: 200px; width: 200px;">Scroll me!</p>
</div>
<p id="output" style="text-align: center;">Waiting on scroll events...</p>
onsearch
– search completed. The onsearch event occurs when the user presses the “ENTER” key or the “x” button on an input element with type=”search”.
Call a function when submitting a search:
<input type="search" onsearch="myFunction()">
onseeked
– the search is over. Handler for the soughted event, which occurs when the user has completed moving to a new audio/video playback position. The onseeked event occurs when the user searches for a new position in the media.
Call the function when the user searches for a new position in the video:
<video onseeked="myFunction()">
This example demonstrates the difference between an onseeking event and an onseeked event:
<video onseeking="myFunction()" onseeked="mySecondFunction()">
Using the currentTime property of a Video object to display the current position during playback when the user has finished moving/moving to a new position:
// Get the video element:
const video = document.getElementById("myVideo");
// Attach a seeked event to the video element:
video.addEventListener("seeked", myFunction);
// Function to display the time position of the playback:
function myFunction() {
document.getElementById("demo").innerHTML = video.currentTime;
}
onseeking
– search is active. Handler for the seeking event, which occurs when the user begins moving to a new audio/video playback position. The onseeking event occurs when the user begins searching for a new position in the media.
Call the function when the user starts moving/moving to a new position in the video:
<video onseeking="myFunction()">
onselect
– selecting some text or value. A handler for the select event, which is when the user selects some text within an element using the mouse or keyboard. The onselect event occurs after some text is selected in an element. The onselect event is most often used for input type=”text” or textarea elements.
Here onSelect is used on the valueField Text object to call the selectState function.
<INPUT TYPE="text" VALUE="" NAME="valueField" onSelect="selectState()">
Call a function when some text is selected:
<input type="text" onselect="myFunction()">
Using the select() method of an input HTML DOM text object to select some text field content. When this happens, the onselect event is fired, which triggers the alert function.
// Select the contents of a text field
function mySelectFunction() {
document.getElementById("myText").select();
}
// Alert some text when the text in the text field has been selected
function myAlertFunction() {
alert("You selected some text!");
}
onshow
– item display. A handler for the show event, which occurs when the menu element is displayed as a context menu. The onshow event occurs when a menu element is shown as a context menu.
See also...![]() New method for observing individual atoms confirms century-old quantum mechanical theory |
Call the function when the menu element is displayed as a context menu:
<div contextmenu="mymenu">
<p>Right-click inside this box to see the context menu!
<menu type="context" id="mymenu" onshow="myFunction()">
<menuitem label="Refresh" onclick="window.location.reload();"></menuitem>
</menu>
</div>
onstalled
– The browser is unable to obtain media data for any reason. A handler for the stalled event, which occurs when the browser tries to obtain media data, but it is not available. The onstalled event occurs when the browser attempts to retrieve unavailable media data.
Call the function when the browser tries to retrieve unavailable media:
<video onstalled="myFunction()">
onsubmit
– confirmation of submission of form data. Handler for the submit event, which occurs when the form is submitted. Executes JavaScript code when the submit event occurs; that is, when the user submits the form to the server. You can use onSubmit to prevent the form from being submitted; To do this, place a return statement that returns false in this event handler. Any other values allow the form to be submitted. If there is no return statement, the form will be submitted.
Here onSubmit calls the validate function to calculate the data being submitted. If the data is correct, the form is submitted; otherwise the form is not submitted.
<FORM onSubmit="return validate(this)"> ... </FORM>
Calling a function when a form is submitted:
<form onsubmit="myFunction()"> Enter name: <input type="text"> <input type="submit"> </form>
onsuspend
– stop metadata extraction. A handler for the suspend event, which occurs when receiving media file data stops before the full download has completed for any reason. The onsuspend event occurs when the browser does not receive media data. The onsuspend event occurs when a download is prevented or suspended.
Call a function when the browser does not receive media data:
<video onsuspend="myFunction()">
ontimeupdate
– changing the position (time) of file playback, that is, rewinding the file. A handler for the timeupdate event, which occurs when the audio/video playback position has changed (for example, when the user has selected a playback point much further from the current one). The ontimeupdate event occurs when the media playback time changes. The ontimeupdate event occurs while media is playing. The ontimeupdate event occurs when the user moves the playback position.
Call the function when the playback time has changed:
<video ontimeupdate="myFunction()">
Using the currentTime property to set the current playback position to 5 seconds:
document.getElementById("myVideo").currentTime = 5;
ontoggle
– the user opens or closes the details element Handler for the toggle event that occurs when the user opens or closes the details element. The ontoggle event occurs when the user opens or closes the details element. The details element specifies additional information that the user can view or hide upon request.
Call a function when the details element is opened or closed:
<details ontoggle="myFunction()">
onunload
– The loading is completed, after which the document is closed. The onunload event occurs after the page has unloaded (or the browser window has been closed). onunload occurs when the user navigates away from the page (by clicking a link, submitting a form, closing the browser window, etc.). Note. The onunload event is also fired when the user reloads the page (and the onload event). Use onUnload with BODY or FRAMESET tags, for example, BODY onUnload=”…”. Regarding frames and framesets, the frame’s onUnload handler (placed in the BODY tag) appears before the frameset’s onUnload handler (placed in the FRAMESET tag) appears.
Call the function when the user unloads the document:
<body onunload="myFunction()">
Here onUnload calls the cleanUp function to do some finishing processing when the user exits the page (closes it):
<BODY onUnload="cleanUp()">
onvolumechange
– volume changed. Handler for the volumechange event, which occurs when the sound volume value changes (including muting the sound completely). The onvolumechange event occurs when the media volume changes. The onvolumechange event occurs when the volume increases or decreases. The onvolumechange event occurs when audio is muted or unmuted.
Call a function when the video volume changes:
<video onvolumechange="myFunction()">
Using the Volume property to set volume:
document.getElementById("myVideo").volume = 0.2;
onwaiting
– waiting for playback to resume. A handler for the waiting event, which occurs when a media file is stopped but is waiting to resume running (for example, when the file pauses to buffer remaining data). The onwaiting event occurs when the media must wait for the next frame.
Call the function when the video is stopped because the next frame needs to be buffered:
<video onwaiting="myFunction()">







