Get Mouse event target element name in JavaScript

Description

The following code shows how to get Mouse event target/source element name.

Example


<html>
<head>
<title>Mouse Events Example</title>
<script type="text/javascript">
  function handleEvent(oEvent) {<!-- w w  w.  j a  v  a  2  s. c o m-->
    var oTextbox = document.getElementById("txt1");
    oTextbox.value += "\n" + oEvent.type;
    oTextbox.value += "\n    target is " + oEvent.srcElement.tagName;

    if (oEvent.fromElement) {
      oTextbox.value += "\n    fromElement is "
          + oEvent.fromElement.tagName;
    }

    if (oEvent.toElement) {
      oTextbox.value += "\n    toElement is " + oEvent.toElement.tagName;
    }

  }
</script>
</head>
<body>
  <P>Use your mouse to click click the red square and move out.</p>
  <div style="width: 100px; height: 100px; background-color: red"
    onmouseout="handleEvent(event)" onclick="handleEvent(event)" id="div1"></div>
  <P>
    <textarea id="txt1" rows="15" cols="50"></textarea>
  </p>
</body>
</html>

Click to view the demo





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window