HTML Attribute Method:
<button onclick="func()"> click me </button>
DOM Property Method:
<input id="elem" type="button" value="Click me">
<script>
elem.onclick = function() {
alert('Thank you');
};
</script>
addEventListener Method:
element.addEventListener("click", func1, [options]); // to add an event listener and handler
element.addEventListener("click", func2, [options]); // useful to add same event handlers or if you have multiple elements
Options:
once // listener automatically removed after triggered
capture // phase where to handle the event:
passive // listener would never call preventDefault()
Event propagation:
bubbling: events run up to its parent and onto other ancestors
capturing: events go down to the element
target: event reached the target element
event.stopPropagation() // prevents further propagation
removeEventListener:
element.removeEventListener("click", func2) // to remove an event listener that was added
More Information:
event.target // where event was dispatched
this // can be used inside event handlers, refers to event.currentTarget
Different ways to add events to elements.
onabort // when resource was not fully loaded
oncanplay // when media can start playing
oncanplaythrough // when media can play through to the end without buffering (fully loaded)
oncuechange // when track element has changed the currently displaying cues
ondurationchange // when the length of the media changes
onemptied // when media has become empty, if load needs to reload media
onended // when media has reach the end
onerror // when media could not be loaded due to an error
onloadeddata // when media data is loaded
onloadedmetadata // when the metadata has been loaded
onloadstart // when browser has started to load a resource
onpause // when media has entered its paused state
onplay // when the paused property is changed from true to false
onplaying // when media has started and currently playing
onprogress // when browser is in the process of getting media data
onratechange // when the playback rate changes, fast forward or slow
onseeked // when seeking attribute is changed to false, user moves to different position in media
onseeking // when seeking attribute is changed to true, media is seeking a new position
onstalled // when browser is unable to fetch media data for any reason
onsuspend // when media data loading has been suspended
ontimeupdate // when time indicated by currentTime attribute has been updated
onvolumechange // when volume or muted attribute has changed
onwaiting // when playback has stopped because of temporary lack of data
Media events work with content such as video, images, and audio. In media element such as <audio>, <embed>, <img>, <object>, and <video>.
<button id="toggleButton">Toggle Box</button>
<div class="box"></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("#toggleButton").click(function() {
$(".box").toggleClass("show");
});
});
</script>
JQuery is a JavaScript library to add interactivity, such as DOM manipulation, event handling, and AJAX calls.
onclick="func()" // when element is clicked on
oncontextmenu // when element is right clicked on
ondblclick // on double click
onmousedown // mouse pressed down on
onmousemove // when mouse is moving over an element
onmouseout // when mouse moves out of an element or one it's children
onmouseleave // when mouse moves out of the element and all it's children
onmouseover // mouse moves over an element or it's children
onmouseenter // mouse enters specified element only
onmousewheel // use onwheel instead
onwheel // when mouse wheel rolls up or down over an element
toggle event:
ontoggle // when user opens or closes details element
HTML mouse event attributes, to execute JavaScript code when certain events happen on elements. Mouse events also have coordinates.
Window-relative coordinates: clientX/clientY.
Document-relative coordinates: pageX/pageY.
onkeydown // when a key is pressed down on
onkeypress // when a user presses a key
onkeyup // when a user lets go of a key
Keyboard keys and codes:
Keyboard Event Tester
event.key // gets the character
event.code // gets physical key code
event.repeat // set to true if auto-repeated
HTML keyboard event attributes.
ondrag // when an element is dragged
ondragend // at the end of a drag
ondragenter // when an element has been dragged to a valid drop target
ondragleave // when an element leaves a valid drop target
ondragover // when an element is being dragged over a valid drop target
ondragstart // at the start of a drag
ondrop // when dragged element is being dropped
onscroll // when an element's scrollbar is being scrolled
Events to use when dragging an element.
ontouchcancel // a touch is interrupted
ontouchend // when one or more touch points are removed from the touch surface
ontouchmove // when one or more touch points are moved along the touch surface
ontouchstart // when one or more touch points are placed on the touch surface
Similiar to mouse events but for touch screens.
pointerdown // when pointer becomes active
pointerup // when pointer is no longer active
pointermove // when pointer changes coordinates
pointerover // when pointer is moved into an element
pointerout // when pointer is moved out of an element
pointerenter // when pointer enters an element or into one of it's children
pointerleave // when pointer is moved out of an element or out of one it's children
pointercancel // when browser determines there are unlikely to be any more pointer events
setpointercapture // used to designate a specific element as the capture target of future pointer events
gotpointercapture // when an element captures a pointer using setPointerCapture()
lostpointercapture // when a captured pointer is released
Pointer events are similiar to mouse events but work primarily with the cursor.
onblur // when element loses focus
onchange // when element's value is changed
oncontextmenu // when a context menu is triggered
onfocus // when element gets focus
oninput // when an element gets user input
oninvalid // when an element is invalid
onreset // when the reset button is clicked
onsearch // when user writes something in a search field (input type="search")
onselect // when some text has been selected in an element
onsubmit // when a form is submitted
Example Submitting Form:
form.addEventListener("submit", (e) => {
e.preventDefault(); // cancels browser's default submit behavior
console.log(input.value)
})
Example Focus Event:
inputEle.addEventListener('focus', e => {
e.target.className = "highlight"
})
Forms and inputs have special properties and events which can be used. Form event attributes to use.
onafterprint // after document is printed
onbeforeprint // before document is printed
onbeforeunload // before document is about to unloaded, useful to ask for additional confirmation before leaving page
onerror // when an error occurs
onhashchange // when there has been changes to the anchor part of the a URL
onload // after the page is finished loading
onmessage // when the message is triggered
onoffline // when the browser starts to work offline
ononline // when the browser starts to work online
onpagehide // when a user navigates away from a page
onpageshow // when a user navigates to a page
onpopstate // when the window's history changes
onresize // when the browser window is resized
onstorage // when a web storage area is updated
onunload // once a page has unloaded (or the browser window has been closed)
DOMContentLoaded // when HTML is fully loaded, DOM tree is built, but external resources may not have yet loaded
Window events work with the browser and window.
oncopy // when user copies content of an element
oncut // when user cuts content of an element
onpaste // when user pastes content in an element
Clipboard events provide information to the clipboard.
CSS Animations:
animationstart // when a css animation has started
animationiteration // when an iteration of a css animation ends and another begins
animationend // when a css animation has completed
animationcancel // when a css animation unexpectedly aborts
CSS Transitions:
transitionstart // when a css transition has started
transitioncancel // when a css transition is canceled
transitionrun // when a css transition is first created, to work with delays
transitionend // when a css transition has completed
Can also listen to css animations and transitions.