CodersTechZone
  • .NET
    • C#
    • ASP.Net
  • HTML
  • Javascript
  • CSS
  • Database
    • SQL Server
    • MYSql
    • Oracle
  • AI
  • TechNews
  • Web-Stories

JavaScript Check Event Target Type: How to Master It in Minutes!

Shawpnendu Bikash Maloroy

June 25, 2024
javascript check event target type
Spread the love

“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?
  • Why Check the Event Target Type is Necessary?
  • How to Check Event Target Type
    • Using Basic Type Check
    • Output
    • Code Explanation
    • Using instanceof
    • Output
  • Common Event Targets and Their Types
  • JavaScript Check Event Target Type: Some Practical Examples
    • Code Example 1: Highlighting Input Fields
    • Code Example 2: Handling Button Clicks
    • Code Example 3: Checking Event Target Type with tagName
  • What is the difference between current target and target event?
    • Output
  • JavaScript Check Event Target Type: 3 Tips to Follow
  • Conclusion

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

JavaScript check event target type using event.target and tagname
buymeacoffee

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.

Note

If you look carefully the output you can see that tagname returns type is only input for the checkbox. Incase of radio button the tagname also return the same type “input”. So you can’t distingusih the difference among HTML input elements. To solve this issue either use JQuery selectors or use class name of the elements instead of tagname directly. Look at our “Code Example 2: Handling Button Clicks” section.

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

JavaScript check event target type using instanceof

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 ElementJavaScript Type
buttonHTMLButtonElement
inputHTMLInputElement
divHTMLDivElement
aHTMLAnchorElement
spanHTMLSpanElement
formHTMLFormElement
selectHTMLSelectElement
textareaHTMLTextAreaElement
Table: List of Event Targets and Their Types
buymeacoffee

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 using currentTarget

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.

Note

JS event.target is a DOM Level 2 feature and is fully supported by all modern browsers.

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!

Shawpnendu Bikash Maloroy
Shawpnendu Bikash Maloroy

๐Ÿ‹๏ธโ€โ™‚๏ธ Discover Code Blocks From 20+ yrs JS Expert
๐Ÿ’ฅ Asp.net C# Developer
๐Ÿ† Solution Architect
๐Ÿ‘จโ€โœˆ๏ธ Database Administrator
๐Ÿ“ข Speaker
๐ŸŽ“ MCTS since 2009

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Spread the love
ยซPrevious
Nextยป

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • 5 Lesser-Known JavaScript Functions
    5 Lesser-Known JavaScript Functions to Boost Your Coding Efficiency
  • 7 Weird JavaScript Tricks That Look Like Bugs
    7 Weird JavaScript Tricks That Look Like Bugs (#3 Will Shock You!)
  • Build a JavaScript Gamer Journal in 8 Lines
    ๐ŸŽฎ Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! ๐Ÿ†
  • JavaScript Pet Feeder Reminder in 7 Lines
    How to Code a Simple JavaScript Pet Feeder Reminder in 7 Lines: Feed Your Pet Like a Coding Boss! ๐Ÿถ
  • 10-line calculator JavaScript
    Build a Simple Calculator in JavaScript: 10 Lines to Wow Your Friends!

About-CodersTech Zone |  Contact |  Disclaimer |  Fact-Checking policy |  Affiliate Disclosure |  Privacy Policy

Copyright ยฉ 2024 CodersTechZone.com