jQuery event.target Property

jQuery | event.target Property: Learn about the jQuery event.target Property with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 28, 2022

event.target Property

An event is an action occurred by the user. Therefore, many functions and methods can be set according to those actions performed. When these actions are defined for an event interface, we term those as the event properties. There are various predefined event properties in jQuery. Here, let's discuss the event.target Property.

The event.target is a built-in property in jQuery. This property helps us to get the element that has triggered the particular event.
Many times, there are situations when the same event is triggered with various different DOM elements. Hence, knowing which amongst them has triggered the particular event would help us to attach the functions for them accordingly.

Also, by using event.target == this, we can check how the events are being handled due to event bubbling.

event.target Property Syntax

event.target

This property takes in one required parameter – event. This event parameter is the one specified in the binding function. The below example shows how the event.target property is triggered when the sentences are clicked.

jQuery event.target Property Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>jQuery Event - Target Property</h2>
    <p>Get to know which element triggeres the event./p>
    <hr>
    <h4 style="color:darkblue">Welcome to Include Help !</h4>
    <p>This is a jQuery Tutorial for Event Methods.</p>
    <h4 style="color:darkblue">Thanks for visiting !</h4>
    <img style="height: 200px;" id="myImg" src="https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=">
    <hr>
    <h3></h3>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('h4, p').click(function(event){
            $('h3').html('Click Event Triggered By: ' + event.target.nodeName);
        });
    
        $('img').hover(function(event){
            $('h3').html('Hover Event Triggered By: ' + event.target.nodeName);
        });
    });
  </script>
</html>

Output:

Example 1: jQuery event.target Property



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.