“Javascript Check Event Target Type” means identifying the HTML DOM element(s) that generate an event. To identify the event target type in JavaScript, we can use this event object. This object contains all information about the event, including the target element.
event.target and event.target.tagName are the two main event properties that we can use to check event target types accurately.
Table of Contents
What is an Event Target?
In JavaScript, an event target is the HTML DOM element that can generate an event. For example, when a user interacts with a web page button element (e.g., clicking or hovering on the button), an event occurs. In this case, the event target is the button element that generates the click or mouse-over event.
Why Check the Event Target Type is Necessary?
There are a lot of reasons to check the event target type. Major use cases are:
- Event Handling: Registering events for each individual element is very difficult. To avoid this hectic job, we can register events group-wise. So that later on, upon an event, we can check the type and take the necessary actions.
- Improved User Experience: Apart from business logic, we can track the event type to develop some fancy features. Like page-wide elements re-ordering, highlighting, etc. to improve user experiences.
- Debugging: In cases of error, especially when we have many types of elements at a huge number or for dynamic events, a type check gives the developer a lifeline to handle errors.
How to Check Event Target Type
As mentioned earlier, we can check the event target type in JavaScript from the event object directly. The event object contains information about the event, including the target element. JS has a lot of event instance properties for type checking. All direct-type checks are given below:
Using Basic Type Check
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Javascript Check Event Target Type</title>
</head>
<style>
p, div{
margin-top:10px;
border: 1px solid black;
}
</style>
<body>
<p>
Its an HTML paragraph. Click on it to check the event target type.
</p>
<div>
Its an HTML DIV. Click on it to check the event target type.
</div>
<div>
<input type="checkbox" id="chkOne" name="chk" value="Click me to chcek my type">
<br>
<input type="radio" id="rdoOne" name="rdo" value="Click me to chcek my type">
</div>
</body>
</html>
<script>
document.addEventListener('click', function(event) {
console.log('Event target:', event.target);
console.log('Event target type:', event.target.tagName);
});
</script>
Output
Code Explanation
In this example, when the user clicks on an element paragraph or div, the event.target property holds the element that was clicked. The tagName property logs the type of the element.
Using instanceof
Another way to check the event target type is by using the instanceof operator. This operator checks if the event target is an instance of a specific class. To learn more, check out the below example:
<script>
// Javascript Check Event Target Type
document.addEventListener('click', function(event) {
if (event.target instanceof HTMLParagraphElement) {
console.log('User click on the Paragraph');
} else if (event.target instanceof HTMLDivElement) {
console.log('User click on the div element');
} else if (event.target instanceof HTMLButtonElement) {
console.log('User click on the button element');
}
});
</script>
Output
Common Event Targets and Their Types
If you look at the above code example, you will notice that we have used three JavaScript types, such as HTMLParagraphElement, HTMLDivElement, and HTMLButtonElement, to define the HTML element type. The table below contains the most commonly used HTML elements and their JavaScript types.
HTML Element | JavaScript Type |
---|---|
button | HTMLButtonElement |
input | HTMLInputElement |
div | HTMLDivElement |
a | HTMLAnchorElement |
span | HTMLSpanElement |
form | HTMLFormElement |
select | HTMLSelectElement |
textarea | HTMLTextAreaElement |
JavaScript Check Event Target Type: Some Practical Examples
Code Example 1: Highlighting Input Fields
If you want to highlight input fields when they are clicked then follow the below code block:
document.addEventListener('click', function(event) {
if (event.target instanceof HTMLInputElement) {
event.target.style.backgroundColor = 'yellow';
}
});
In this example, the background color of input fields changes to yellow when you click on it.
Code Example 2: Handling Button Clicks
If you have multiple buttons and want to handle their clicks individually based on their types, then follow the below code block:
document.addEventListener('click', function(event) {
if (event.target instanceof HTMLButtonElement) {
if (event.target.classList.contains('submit-button')) {
console.log('Submit button clicked');
} else if (event.target.classList.contains('cancel-button')) {
console.log('Cancel button clicked');
}
}
});
In the above code, different actions are taken based on the button’s class.
Code Example 3: Checking Event Target Type with tagName
document.addEventListener('click', function(event) {
if (event.target.tagName === 'BUTTON') {
console.log('Button clicked');
}
});
What is the difference between current target and target event?
currentTarget denotes to which element the event was attached or the element whose eventListener triggered the event. event.target mentions where the event started.
For example, you have a button within the HTML body tag. You attach the click event handler in the body tag, not the button. In this case, whenever the user clicks on the button (within the body), the currentTarget denotes the body, not the button, as the click event handler is attached to the body. Make sense? Let’s look at the example below:
<!DOCTYPE html>
<html>
<!-- JavaScript Check Event Target Type - using currentTarget
click event attached with body -->
<body onclick="raiseEvent(event)" style="border:1px dashed black;Padding:10px">
<p>Click on the below button ...</p>
<button>Click Here</button>
<script>
function raiseEvent(event) {
console.log(event.currentTarget.tagName);
}
</script>
</body>
</html>
Output
JavaScript Check Event Target Type: 3 Tips to Follow
- Use tagName for Simple Checks: Use event.target.tagName to do the basic checks only. Because it’s very easy, straightforward and effective.
- Use instanceof for Specific Types: If you would like to work with a specific HTML element, then use instanceof. Because it provides more control and clarity.
- Combine with Class Names: To get more control on elements, combine type checking with class or ID selectors.
Conclusion
JavaScript check event target type can significantly increase your web development skills. So follow our all examples carefully. It gives you the ability to handle events more accurately and improve user interactions on your web pages. So requesting all of you to practice those and incorporate them into your JS projects from now and onwards.
By using these concepts, you can create more interactive, user-friendly, and fancy web applications.
So practice practice and practice. Happy coding bro!
๐๏ธโโ๏ธ Discover Code Blocks From 20+ yrs JS Expert
๐ฅ Asp.net C# Developer
๐ Solution Architect
๐จโโ๏ธ Database Administrator
๐ข Speaker
๐ MCTS since 2009
Leave a Reply