jQuery Event Object

jQuery Event Object with Examples

In this article, I am going to discuss jQuery Event Object with Examples. Please read our previous article, where we discussed Mouse Events in jQuery. At the end of this article, you will understand everything about the jQuery Event Object.

jQuery Event Object

When a W3C event listener’s event occurs and it calls its associated function, it also passes a single argument to the function – a reference to the event object. The event object contains a number of properties that describe the event that occurred. For example, the event object contains event data like, the X and Y coordinates of the mouse pointer when the event occurred, the HTML element that fired the event, which mouse button is clicked, etc.

Query’s event system normalizes the event object according to W3C Standards. The event object is guaranteed to be passed to the event handler. Most properties from the original event are copied over and normalized to the new event object.

Here the list of event object properties is given
  1. event.currentTarget: The current DOM element within the event bubbling phase.
  2. event.data: An optional object of data passed to an event method when the current executing handler is bound.
  3. event.delegateTarget: Returns the element where the currently-called jQuery event handler was attached.
  4. event.isDefaultPrevented(): Returns whether event.preventDefault() was ever called on this event object.
  5. event.isImmediatePropagationStopped(): Returns whether event.stopImmediatePropagation() was ever called on this event object.
  6. event.isPropagationStopped(): Returns whether event.stopPropagation() was ever called on this event object.
  7. event.metaKey: Indicates whether the Windows key or Command key (on Mac keyboard) was pressed when the event fired.
  8. event.namespace: Returns the namespace specified when the event was triggered.
  9. event.pageX: Returns the mouse position relative to the left edge of the document.
  10. event.pageY: Returns the mouse position relative to the top edge of the document.
  11. event.preventDefault(): If this method is called, the default action of the event will not be triggered.
  12. event.relatedTarget: Returns the other DOM element involved in the event, if any.
  13. event.result: The last or previous value returned by an event handler that was triggered by this event.
  14. event.stopImmediatePropagation(): Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.
  15. event.stopPropagation(): Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
  16. event.target: Returns the DOM element that triggered the event.
  17. event.timeStamp: Returns difference in milliseconds between the time the event is triggered and January 1, 1970.
  18. event.type: Returns the type of event that was triggered.
  19. event.which: Indicates the specific key or button that was pressed for key or mouse events.
Example: jQuery Event Object

Obtaining the event object is very simple. The event object is always passed to the event handler method. Let us understand this with an example. When we click the button, we want to retrieve the following event properties

  1. Name of the event.
  2. X co-ordinate of the mouse pointer when the event occurred.
  3. Y co-ordinate of the mouse pointer when the event occurred.
  4. Type of the DOM element that was triggered due to the event.
  5. The tag name of the DOM element that was triggered due to the event.

In the below example, we are passing event objects to getEventDetails() method. This object is the raw JavaScript event object. The type property gives us the event name that occurred. pageX and pageY properties return the X and Y coordinates of the mouse pointer. Target property returns the HTML element that raised the event. Target, pageX, and pageY properties are supported by all modern browsers and Internet Explorer 9 and above. The below example code will not work in Internet Explorer 8 and earlier versions. In addition to the click event, the following example returns mouseover and mouseout event data.

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      body {
        font-family: Arial, Helvetica, sans-serif;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
      }
      p {
        margin: 20px;
        font-weight: bold;
        font-size: 30px;
        text-align: center;
        font-style: oblique;
      }
      #btn {
        background-color: #1c4450;
        border: none;
        outline: none;
        color: white;
        padding: 20px 35px;
        margin: 20px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        border-radius: 10px;
        cursor: pointer;
        transition-duration: 0.4s;
        text-transform: uppercase;
      }
      #btn:hover {
        box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
          0 17px 50px 0 rgba(0, 0, 0, 0.19);
      }
      h1 {
        font-size: 40px;
        margin-bottom: 30px;
        padding: 30px;
        text-align: center;
        text-transform: capitalize;
        font-style: italic;
      }
    </style>
  </head>
  <body>
    <h1>jQuery Event Object</h1>
    <div class="container">
      <input
        id="btn"
        type="button"
        value="Use me to retrieve the event properties"
      />

      <p id="Result"></p>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#btn")
          .click(function () {
            getEventDetails(event);
          })
          .mouseover(function () {
            getEventDetails(event);
          })
          .mouseout(function () {
            getEventDetails(event);
          });

        function getEventDetails(event) {
          var eventDetails = `Event = 
            ${event.type} 
            <br/> X = 
            ${event.pageX}
            <br/>Y = 
            ${event.pageY} 
            <br/>Target Type = 
            ${event.target.type}
            <br/>Target Tag Name = 
            ${event.target.tagName}
            `;

          $("#Result").html(eventDetails);
        }
      });
    </script>
  </body>
</html>

Now run the above code and you will get the following output in the browser.

jQuery Event Object with Examples

Now when you mouseover over the “Use me to retrieve the event properties”, the mouseover event is fired and it will give the event details as shown in the below image.

Event Object in jQuery with Examples

Now when you mouse out from the “Use me to retrieve the event properties”, the mouse out event is fired and it will give the event details as shown in the below image.

jQuery Event Object

Now when you click on the “Use me to retrieve the event properties”, the click event is fired and you will get the event details as shown in the below image.

jQuery Event Object Examples

Cross Browser Solution:

For the above code (our first example) to work in all browsers including Internet Explorer 8 and earlier versions, we need to pass the event object to the mouse events such as click(), mouseover() & mouseout(). When the event object is passed inside the callback of jQuery mouse events, that is going to be the jQuery event object. As we know jQuery normalizes the event object for cross-browser support. So, the following code is going to work in all browsers.

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      body {
        font-family: Arial, Helvetica, sans-serif;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
      }
      p {
        margin: 20px;
        font-weight: bold;
        font-size: 30px;
        text-align: center;
        font-style: oblique;
      }
      #btn {
        background-color: #1c4450;
        border: none;
        outline: none;
        color: white;
        padding: 20px 35px;
        margin: 20px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        border-radius: 10px;
        cursor: pointer;
        transition-duration: 0.4s;
        text-transform: uppercase;
      }
      #btn:hover {
        box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
          0 17px 50px 0 rgba(0, 0, 0, 0.19);
      }
      h1 {
        font-size: 40px;
        margin-bottom: 30px;
        padding: 30px;
        text-align: center;
        text-transform: capitalize;
        font-style: italic;
      }
    </style>
  </head>
  <body>
    <h1>jQuery Event Object</h1>
    <div class="container">
      <input
        id="btn"
        type="button"
        value="Use me to retrieve the event properties"
      />

      <p id="Result"></p>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#btn")
          .click(function (event) {
            getEventDetails(event);
          })
          .mouseover(function (event) {
            getEventDetails(event);
          })
          .mouseout(function (event) {
            getEventDetails(event);
          });

        function getEventDetails(event) {
          var eventDetails = `Event = 
            ${event.type} 
            <br/> X = 
            ${event.pageX}
            <br/>Y = 
            ${event.pageY} 
            <br/>Target Type = 
            ${event.target.type}
            <br/>Target Tag Name = 
            ${event.target.tagName}
            `;

          $("#Result").html(eventDetails);
        }
      });
    </script>
  </body>
</html>

The above example will give you the same output as the previous example.

Example:

Now let us see some more event object properties. In the below example, we are using event.currentTarget, event.delegateTarget, event.timeStamp, event.metaKey, and event.relatedTarget propertirs.

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      body {
        font-family: Arial, Helvetica, sans-serif;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
      }
      p {
        margin: 20px;
        font-weight: bold;
        font-size: 30px;
        text-align: center;
        font-style: oblique;
      }
      #btn {
        background-color: #1c4450;
        border: none;
        outline: none;
        color: white;
        padding: 20px 35px;
        margin: 20px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        border-radius: 10px;
        cursor: pointer;
        transition-duration: 0.4s;
        text-transform: uppercase;
      }
      #btn:hover {
        box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
          0 17px 50px 0 rgba(0, 0, 0, 0.19);
      }
      h1 {
        font-size: 40px;
        margin-bottom: 30px;
        padding: 30px;
        text-align: center;
        text-transform: capitalize;
        font-style: italic;
      }
    </style>
  </head>
  <body>
    <h1>jQuery Event Object</h1>
    <div class="container">
      <input
        id="btn"
        type="button"
        value="Use me to retrieve the event properties"
      />

      <p id="Result"></p>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#btn").mouseover(function (event) {
          getEventDetails(event);
        });

        function getEventDetails(event) {
          var eventDetails = `Event Target= 
            ${event.currentTarget.type} 
            <br/>Delegate Target = 
            ${event.delegateTarget.type} 
            <br/> Time Stamp = 
            ${event.timeStamp}
            <br/>Meta Key = 
            ${event.metaKey}
            <br/>Related Target = 
            ${event.relatedTarget.tagName}
            `;

          $("#Result").html(eventDetails);
        }
      });
    </script>
  </body>
</html>

Now run the above code and put the mouse pointer on the Use me to retrieve the event properties button and you will get the following output.

event.currentTarget, event.delegateTarget, event.timeStamp, event.metaKey, and event.relatedTarget propertirs

Example: event.preventDefault() and event.isDefaultPrevented()

In the below example, we will see the two properties i.e. event.preventDefault() and event.isDefaultPrevented().

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      body {
        font-family: Arial, Helvetica, sans-serif;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
      }
      p {
        margin: 20px;
        font-weight: bold;
        font-size: 30px;
        text-align: center;
        font-style: oblique;
      }
      a {
        background-color: #1c4450;
        border: none;
        outline: none;
        color: white;
        padding: 20px 35px;
        margin: 20px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        border-radius: 10px;
        cursor: pointer;
        transition-duration: 0.4s;
        text-transform: uppercase;
      }
      a:hover {
        box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
          0 17px 50px 0 rgba(0, 0, 0, 0.19);
      }
      h1 {
        font-size: 40px;
        margin-bottom: 30px;
        padding: 30px;
        text-align: center;
        text-transform: capitalize;
        font-style: italic;
      }
    </style>
  </head>
  <body>
    <h1>jQuery Event Object</h1>
    <div class="container">
      <a href="https://www.google.com/" id="prevent"
        >www.google.com(Prevent Default)</a
      >
      <a href="https://www.google.com/">www.google.com</a>

      <p id="Result"></p>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#prevent").click(function (event) {
          event.preventDefault();
          $("#Result").html(event.isDefaultPrevented());
        });
      });
    </script>
  </body>
</html>

The default behavior of the anchor tag is to redirect to the given address. But we can prevent that default behavior. Notice that in the first anchor tag we have used prevent default method. This is not going to www.google.com. And in the result <p> the Boolean value is showing that we have used the prevent default method in the event as shown in the below image.

event.preventDefault() and event.isDefaultPrevented() in jQuery

But when you click on the 2nd button, it is navigating to the www.google.com

Example: event.stopPropagation() and event.isPropagationStopped()

In the below example, we are going to learn event.stopPropagation() and event.isPropagationStopped() method.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <style>
      body {
        font-family: Arial, Helvetica, sans-serif;
      }
      .container {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        background-color: rgb(164, 255, 192);
        padding: 20px;
        border: 2px solid black;
      }
      h1 {
        font-size: 40px;
        margin-bottom: 30px;
        padding: 30px;
        text-align: center;
        text-transform: capitalize;
        font-style: italic;
      }
      .demo {
        margin: 20px auto;
        font-weight: bold;
        font-size: 30px;
        text-align: center;
        font-style: oblique;
        width: 90%;
        padding: 20px;
        border-radius: 30px;
        background-color: rgb(255, 164, 164);
        cursor: pointer;
      }
      button {
        background-color: #1c4450;
        border: none;
        color: white;
        padding: 15px 20px;
        text-align: center;
        text-decoration: none;
        outline: none;
        font-size: 20px;
        border-radius: 10px;
        cursor: pointer;
      }
      #result {
        margin: 20px;
        font-weight: bold;
        font-size: 30px;
        text-align: center;
        font-style: oblique;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h1>jQuery event object</h1>

      <p class="demo">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum,
        odio neque veritatis ullam velit illum at obcaecati necessitatibus quos
        eveniet.
      </p>
      <button>Click Me</button>
      <p id="result"></p>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function () {
        $("div").click(function () {
          alert("Div element is clicked");
        });
        $("h1").click(function () {
          alert("h1 element is clicked");
        });
        $("p").click(function () {
          alert("P element is clicked");
        });
        $("button").click(function (event) {
          event.stopPropagation();
          alert("Button element is clicked");
          $("#result").html(event.isPropagationStopped());
        });
      });
    </script>
  </body>
</html>

Notice this carefully. Click on the <p> element. At first alert for the p element is displayed as shown in the below image.

event.stopPropagation() and event.isPropagationStopped() method in jQuery

Once you click on the OK button, the alert for the div element is displayed as shown in the below image.

jQuery Event Object with Examples

Then the alert for <div> element is also displayed. Because <p> is inside the <div> and when we click on the p element <div> is also clicked actually. This is called event bubbling. To prevent this we use event.stopPropagation(). Now, click on the Click Me button, which is also inside the <div> but we have prevented that event from bubbling.

jQuery Event Object

Here only the alert for the button is displayed. Once you click on the OK button, the Boolean value is showing that we have used stop propagation in the event as shown in the below image.

Event Object in jQuery

In the next article, I am going to discuss How jQuery Detect Which Mouse Button is Clicked with Examples. Here, in this article, I try to explain jQuery Event Object with Examples and I hope you enjoy this jQuery Event Object article.

In the next article, I am going to discuss How jQuery Detect Which Mouse Button is Clicked with Examples. Here, in this article, I try to explain jQuery Event Object with Examples and I hope you enjoy this jQuery Event Object article.

Leave a Reply

Your email address will not be published.