JavaScript Events
1. What are events
Events are "things"
that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can react
on these events. Some of the examples of HTML events are,
- Web page has finished loading
- Input field was changed
- Button was clicked
<!doctype html>
<html>
<head>
<script>
function greeting() {
alert('Hello! Good morning');
}
</script>
</head>
<body>
<button type="button" onclick="greeting()">Click me</button>
</body>
</html>
2. How do you detect caps lock key turned on or not
The mouseEvent getModifierState()
is used to return a boolean value that indicates whether the specified modifier key is activated or not. The modifiers such as CapsLock, ScrollLock and NumLock are activated when they are clicked, and deactivated when they are clicked again.
<input type="password" onmousedown="enterInput(event)" />
<p id="feedback"></p>
<script>
function enterInput(e) {
var flag = e.getModifierState("CapsLock");
if (flag) {
document.getElementById("feedback").innerHTML = "CapsLock activated";
} else {
document.getElementById("feedback").innerHTML = "CapsLock not activated";
}
}
</script>
3. What is an event flow
Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event for each of its parent elements first, starting at the top with the global window object.
There are two ways of event flow:
- Top to Bottom(Event Capturing)
- Bottom to Top (Event Bubbling)
4. What is event bubbling
<div>
<button class="child">Hello</button>
</div>
<script>
const parent = document.querySelector("div");
const child = document.querySelector(".child");
parent.addEventListener("click",
function () {
console.log("Parent");
}
);
child.addEventListener("click", function () {
console.log("Child");
});
</script>
<!-- Child -->
<!-- Parent -->
5. What is event capturing
<div>
<button class="child">Hello</button>
</div>
<script>
const parent = document.querySelector("div");
const child = document.querySelector(".child");
parent.addEventListener("click",
function () {
console.log("Parent");
},
true // Enable Event Capturing
);
child.addEventListener("click", function () {
console.log("Child");
});
</script>
<!-- Parent -->
<!-- Child -->
6. What is the difference between document load and DOMContentLoaded events
The DOMContentLoaded
event is fired when the initial HTML document has been completely loaded and parsed, without waiting for assets(stylesheets, images, and subframes) to finish loading. Whereas The load event is fired when the whole page has loaded, including all dependent resources(stylesheets, images).