100daysofcode - Day05
Hey everyone
, what is going on ??. Today marks the 5th day in our coding challenge.
In Today post we will make a gentle dive in the document object model events, their types and how we can deal with them.
What are the HTML DOM events ? 
Events that allow the JavaScript programming language to add different event handlers on HTML elements. They are a combined with callbacks functions where these functions will only execute if the specified event occur.
Examples of HTML DOM events:
- Loading a webpage
- Loading an image into the browser
- When an input field is changed
- On User keystrokes
- On form submission
And now let’s explore some of the basic events in JavaScript.
-
The load and onload event, that gets fired when the whole page loads, including all the dependencies resources like the external images, stylesheets …
Example:window.addEventListener('load', (event) => { console.log('The entire page and its dependencies is fully loaded'); }); -
The unloaded event is fired when the document or one of its child gets unloaded, it typically execute when the user navigate from one page to another, and this type of events can be used to clean up the references to avoid memory leaks
Example:window.onunload = (event) => { console.log('The page is unloaded successfully'); }; -
The onchange event, that get fired when a user commit a value change to a form control
Example:// A function to count the user message length function countUserMessageLength(e) { console.log(e.target.value.length) } // Select the input element let input = document.querySelector('input'); // Assign the onchange eventHandler to it input.onchange = handleChange; -
The mouseover event, that gets fired at an Element when a pointing device (such as a mouse) is used to move the cursor onto the element or one of its child elements.
Example:<ul id="list"> <li>Javascript</li> <li>MongoDB</li> </ul> let list = document.getElementById("list"); list.addEventListener("mouseover", function( event ) { // on mouseover change the li color event.target.style.color = "orange"; // reset the color after 1000 ms to the original setTimeout(function() { event.target.style.color = ""; }, 1000); }, false); -
The onpaste event, gets fired when the user has initiated a “paste” action through the browser’s user interface.
Example:<div class="source" contenteditable="true">Copy from here ... </div> <div class="target" contenteditable="true">...and pasting it here</div> const target = document.getElementByClassName("target") target.addEventListener('paste', (event) => { let paste = (event.clipboardData || window.clipboardData).getData('text'); paste = paste.toUpperCase(); const selection = window.getSelection(); if (!selection.rangeCount) return false; selection.deleteFromDocument(); selection.getRangeAt(0).insertNode(document.createTextNode(paste)); event.preventDefault(); });