srcElement property (event)
Note that the object on which the event has occurred and the object on which the event listener was registered may be different.
For example, if the user clicks on an element and an event listener for the onclick event is registered on the parent of the element, the listener function will be called (the onclick event bubbles up).
In that case, the event is occurred on a child of the element on which the event listener was registered.
If you need the object on which the listener was registered, use the currentTarget property or the this keyword (inline event handlers) within the listener function.
For further details, please see Example 1 and 2.
In case of activation and mouse move events, the fromElement, toElement and relatedTarget properties can also be useful. For example, the fromElement and relatedTarget properties retrieve the element that the mouse pointer left, in case of the onmouseover event.
Syntax:
Possible values:
Example HTML code 1:
|
||||
<head> <script type="text/javascript"> function ChangeColor (event) { var target = event.target ? event.target : event.srcElement; // if the click has occurred on a button if (target && target.nodeName.toLowerCase () == "button") { target.style.color = "#ff0000"; } } </script> </head> <body> <div onclick="ChangeColor (event)"> Clicking on this text does not modify the text color. Clicking on a button modify its text color. <br /><br /> <button>Change my text color to red!</button> <button>Change my text color to red!</button> <button>Change my text color to red!</button> </div> </body> |
||||
|
||||
Did you find this example helpful?
|
Example HTML code 2:
|
||||
<head> <script type="text/javascript"> function ChangeColor (button) { button.style.color = "#ff0000"; } </script> </head> <body> <div> Clicking on this text does not modify the text color. Clicking on a button modify its text color. <br /><br /> <button onclick="ChangeColor (this)">Change my text color to red!</button> <button onclick="ChangeColor (this)">Change my text color to red!</button> <button onclick="ChangeColor (this)">Change my text color to red!</button> </div> </body> |
||||
|
||||
Did you find this example helpful?
|