YouTip LogoYouTip

Jq Event Relatedtarget

## jQuery event.relatedTarget Property The `event.relatedTarget` property in jQuery returns the element that the mouse pointer entered or exited when a mouse event was triggered. This property is highly useful for tracking user navigation patterns, managing complex hover states, and preventing redundant event triggers when moving between parent and child elements. --- ## Definition and Usage The `event.relatedTarget` property identifies the secondary element involved in a mouse event, if one exists. Specifically: * **For `mouseenter` or `mouseover` events:** It returns the element the mouse pointer **left** to enter the current element. * **For `mouseleave` or `mouseout` events:** It returns the element the mouse pointer **entered** after leaving the current element. If there is no related element (for example, if the mouse moved in from outside the browser window), the property returns `undefined` or `null`. --- ## Syntax ```javascript event.relatedTarget ``` ### Parameter Values | Parameter | Description | | :--- | :--- | | `event` | **Required.** The event object passed into the event handler function. | --- ## Code Examples ### Example 1: Basic Usage with `mouseenter` The following example demonstrates how to detect which element the mouse pointer came from when entering a `
` element. ```javascript $("div").mouseenter(function(event) { // Retrieve the node name of the element the mouse just left var comingFrom = event.relatedTarget ? event.relatedTarget.tagName : "outside the window"; console.log("Mouse entered the div. Came from: " + comingFrom); }); ``` ### Example 2: Tracking Source and Destination Elements This example tracks both the element being left and the element being entered during `mouseover` and `mouseout` events. ```html jQuery event.relatedTarget Demo
Parent Box
Child Box

Hover over the boxes to see the related target...

``` --- ## Technical Considerations ### 1. Event Bubbling vs. Specific Events * **`mouseover` and `mouseout`**: These events bubble. When moving between a parent and a child element, these events will fire repeatedly. `event.relatedTarget` is crucial here to filter out unwanted noise and determine if the mouse actually left the parent boundary. * **`mouseenter` and `mouseleave`**: These events do not bubble. They only fire when the pointer enters or leaves the selected element itself. Even so, `event.relatedTarget` can still be used to inspect the boundary transition. ### 2. Browser Compatibility jQuery normalizes `event.relatedTarget` across all modern browsers. In legacy versions of Internet Explorer (IE 8 and below), the native properties used were `fromElement` (for mouseover) and `toElement` (for mouseout). jQuery automatically handles this normalization behind the scenes, allowing you to safely use `event.relatedTarget` in a cross-browser compatible way.
← Event ResultEvent Preventdefault β†’