Event Target

In this chapter you will learn:

  1. How to get information from event target

Deal with event target

The following code listens to the mouse over and mouse out event. Inside the event handler it changes the event target text and color.

<!DOCTYPE HTML><!-- j a  v a 2s. c  om-->
<html>
<head>
<style type="text/css">
p {
  background: gray;
  color: white;
}
</style>
</head>
<body>
  <p>This is a test. 
  </p>
  <p id="block2">This is a test. 
  </p>
  <script type="text/javascript">
    var pElems = document.getElementsByTagName("p");
    for ( var i = 0; i < pElems.length; i++) {
      pElems[i].onmouseover = handleMouseEvent;
      pElems[i].onmouseout = handleMouseEvent;
    }
    function handleMouseEvent(e) {
      if (e.type == "mouseover") {
          e.target.innerHTML += "mouseover";
        e.target.style.background = 'white';
        e.target.style.color = 'black';
      } else {
        e.target.style.removeProperty('color');
        e.target.style.removeProperty('background');
      }
    }
  </script>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. Methods for all html elements
Home » Javascript Tutorial » DOM Event
DOM Events
Event Flow: capture, target, and bubbling
Event Phase
Cancel events
Events Type
Event Target