Skip to main content

Browser Events

Browser Events: Browser Events



What is an event in relation to the DOM, Browser, and JavaScript?

View Answer:
Interview Response: An event in relation to the DOM, browser, and JavaScript refers to an action or occurrence, such as a user interaction or system event, that can be detected, handled, and responded to by JavaScript code for dynamic web page interactions.

Code Example:

<button id="myButton">Click Me</button>

<script>
// Add event listener to the button
var button = document.getElementById("myButton");
button.addEventListener("click", handleClick);

// Event handler function
function handleClick(event) {
console.log("Button clicked!");
// Additional code logic here...
}
</script>

In this example, we have an HTML button with the id "myButton". We use JavaScript to get a reference to the button using document.getElementById(). Then, we add an event listener to the button using addEventListener(). When the button is clicked, the handleClick function is called, which logs a message to the console. You can add additional code logic inside the event handler function to perform actions in response to the event.


Can you name at least three DOM events?

View Answer:
Interview Response: There are several DOM events, including mouse, keyboard, form element, document, and CSS events. The most common is mouse and keyboard events, like mouse `click` and keyboard `keydown` events.

What is a JavaScript event handler?

View Answer:
Interview Response: A JavaScript event handler is a function that is assigned to handle and respond to specific events triggered by user interactions or system events. It executes code in response to those events.

Code Example:

<button id="myButton">Click Me</button>

<script>
// Event handler function
function handleClick(event) {
console.log("Button clicked!");
// Additional code logic here...
}

// Add event listener to the button
var button = document.getElementById("myButton");
button.addEventListener("click", handleClick);
</script>

In this example, we have a button with the id "myButton". The handleClick function is an event handler that is called when the button is clicked. It logs a message to the console. We then add an event listener to the button using addEventListener(), specifying the "click" event and the handleClick function as the event handler.


Can you execute an event in an HTML attribute?

View Answer:
Interview Response: Yes, you can execute an event in an HTML attribute using inline event handlers like `onclick`, `onmouseover`, etc., where you directly specify the JavaScript code to be executed when the event occurs.

Technical Response: You can set an event handler in HTML with an attribute named on‹event›. The onevent handlers are properties on particular DOM elements to manage how that element reacts to events. Elements can be interactive (links, buttons, images, forms, and more.) or non-interactive (such as the base ‹body› element). The onevent handler usually gets named with the event it reacts to, like onclick, onkeypress, and onfocus. You can specify an on‹…› event handler for a particular event (such as click) for a given object differently. An HTML attribute is not a convenient place to write tons of code. So, it gets recommended to us that we write an event handler. As we know, HTML attribute names are not case-sensitive, so ONCLICK works as well as onClick and onCLICK… But usually, attributes are lowercased: onclick.

Code Example: HTML Event Attribute onclick

<!-- alerts Click! in the browser -->
<input value="Click me" onclick="alert('Click!')" type="button">

Code Example: Event Handler (recommended)

<script>
function countRabbits() {
for (let i = 1; i <= 3; i++) {
alert('Rabbit number ' + i);
}
}
</script>

<input type="button" onclick="countRabbits()" value="Count rabbits!" />

Can you connect a handler with a DOM element "on<event>" property?

View Answer:
Interview Response: Yes, we can assign a handler using a DOM property on‹event›. If the handler is assigned using an HTML attribute, the browser reads it, creates a new function from the attribute content, and writes it to the DOM property. This action is similar to using a function as an event handler, but it’s less direct.

Code Example:

<input id="elem" type="button" value="Click me" />
<script>
elem.onclick = function () {
alert('Thank you');
};
</script>

Is it possible to utilize an event on a DOM element more than once?

View Answer:
Interview Response: No, a DOM element can only have one event listener of a particular event type attached to it at a time. Repeatedly adding an event listener of the same type will replace the previous one.

Code Example:

<input type="button" id="elem" onclick="alert('Before')" value="Click me" />
<script>
elem.onclick = function () {
// overwrites the existing handler
alert('After'); // only this After will be shown
};
</script>

What is the reason for not using setAttribute for handlers?

View Answer:
Interview Response: Using setAttribute for event handlers is not recommended because it treats the handler code as a string, leading to potential security risks and limited functionality compared to directly assigning a function as an event handler.

Code Example: This will not work!

// a click on <body> will generate errors,
// because attributes are always strings, function becomes a string
document.body.setAttribute('onclick', function () {
alert(1);
});

Are DOM properties names case-sensitive or case-insensitive?

View Answer:
Interview Response: DOM property names are case-sensitive in JavaScript, meaning that differences in letter case (uppercase vs. lowercase) are considered significant when accessing or setting property values on DOM elements. We should assign a handler to elem.onclick, not elem.ONCLICK.

Code Example: element.innerHTML

var element = document.createElement('div');
element.innerHTML = 'Hello, JavaScript!';

console.log(element.innerHTML); // Output: Hello, JavaScript!
console.log(element.innerhtml); // Output: undefined

Can you explain the function of the EventTarget addEventListener method?

View Answer:
Interview Response: The EventTarget method addEventListener(event, target, options) sets up a function call whenever the specified event is delivered to the target. Typical targets are Element, Document, and Window, but the target may be any object that supports events (such as XMLHttpRequest).

Syntax:

target.addEventListener(event, handler [, options]);
target.addEventListener(event, handler [, useCapture]);
target.addEventListener(event, handler [, useCapture, wantsUntrusted
// This API has not been standardized.
]); // Gecko/Mozilla only

Code Example:

<input id="elem" type="button" value="Click me" />

<script>
function handler1() {
alert('Thanks!');
}

function handler2() {
alert('Thanks again!');
}

elem.onclick = () => alert('Hello');
elem.addEventListener('click', handler1); // Thanks!
elem.addEventListener('click', handler2); // Thanks again!
</script>

Can we remove an event listener?

View Answer:
Interview Response: You can remove an event listener using the removeEventListener() method, providing the same parameters as when you added it with addEventListener().

Technical Response: To remove an event that gets added, use the removeEventListener(event, handler) function. We should pass the same function that we previously allocated to delete a handler. We cannot remove the function if it does not get stored in a variable. There are no techniques available for "reading back" handlers given by addEventListener.

Code Example:

<script>
function handler() {
alert('Thanks!');
}

input.addEventListener('click', handler);
// ....
input.removeEventListener('click', handler);
</script>

Are there any events that you cannot assign using a DOM property?

View Answer:
Interview Response: Yes, there are events that a DOM property cannot assign. Only when using addEventListener. The DOMContentLoaded event, for example, is triggered when the page is loaded and the DOM gets created, and the addEventListener method is more adaptive in this case.

Code Example:

// will never run
document.onDOMContentLoaded = function() {
alert("DOM built");
};

// this way it works
document.addEventListener("DOMContentLoaded", function() {
alert("DOM built");
});

What is the event object used for in JavaScript?

View Answer:
Interview Response: Web developers use the event object for various actions, including getting the event type, current target, and window relative coordinates of the current during point events. The event object can be called directly in HTML attributes or inside our scripts.

Code Example:

<!-- event.type returns the type of event (onclick: click) -->
<input type="button" onclick="alert(event.type)" value="Event type" />


Are we limited to just function handlers in JavaScript?

View Answer:
Interview Response: We can assign not just a function but also an object as an event handler using addEventListener. When an event occurs, the object handler method gets invoked, and we could also use a class as another approach.

Code Example: Regular Object

<button id="elem">Click me</button>

<script>
let obj = {
handleEvent(event) {
alert(event.type + ' at ' + event.currentTarget);
},
};

elem.addEventListener('click', obj);
</script>

Code Example: Class

<button id="elem">Click me</button>

<script>
class Menu {
handleEvent(event) {
switch (event.type) {
case 'mousedown':
elem.innerHTML = 'Mouse button pressed';
break;
case 'mouseup':
elem.innerHTML += '...and released.';
break;
}
}
}

let menu = new Menu();
elem.addEventListener('mousedown', menu);
elem.addEventListener('mouseup', menu);
</script>

What's the difference between "event.target" and "event.currentTarget"?

View Answer:
Interview Response: In an event handler, `event.target` refers to the actual element that triggered the event, while `event.currentTarget` refers to the element to which the event handler is attached (the element on which the event listener was registered).

Code Example:

<!DOCTYPE html>
<html>
<head>
<title>Event Target vs CurrentTarget</title>
</head>
<body>
<div id="outer">
<div id="inner">
Click me!
</div>
</div>

<script>
function handleClick(event) {
console.log('Target:', event.target.id);
console.log('CurrentTarget:', event.currentTarget.id);
}

var outer = document.getElementById('outer');
var inner = document.getElementById('inner');

outer.addEventListener('click', handleClick);
inner.addEventListener('click', handleClick);
</script>
</body>
</html>

Output:

Target: inner
CurrentTarget: outer

In the example, we have an outer <div> with an id of "outer" and an inner <div> with an id of "inner". Both elements have a click event listener attached to them.

When you click on the inner <div>, the event bubbles up to the outer <div>. The event handler handleClick is called, and within the function, event.target refers to the element that triggered the event (in this case, the inner <div> with the id "inner"). On the other hand, event.currentTarget refers to the element that currently has the event listener attached to it (in this case, the outer <div> with the id "outer").

Running the code and inspecting the console will display the following output when clicking on the inner <div>:

This demonstrates the difference between event.target and event.currentTarget.