I try to understand javascript target event property

From some examples I tried to make my own target function, but doesn’t work :). Someone please tell me what I did wrong.


 <h1>List King</h1>
 <h2>New Account</h2>
 <div id="feedback"></div>


function checkTarget(e) {
        var el, elMsg;
        if (!e) {
          e = window.event;
        el = e.target || e.srcElement;
        elMsg = el.tagName;
        elMsg.innerHTML = "Target is: " + elMsg;
var elName = document.getElementById('feedback');
elName.addEventListener('click', function(e) {
      }, false);

Two things occur to me at a glance: div#feedback needs to have some CSS applied to it to make it clickable (currently it is an empty div).

  width: 350px;
  height: 350px;
  background: pink;

And this:
elMsg.innerHTML = "Target is: " + elMsg;
should be:
el.innerHTML = "Target is: " + elMsg;

Pullo I understand your point, but on w3schools on target example they don’t have any css and on what you click will show, display the name of that element. This is their example:

<body onclick="myFunction(event)">

<p>Click on any elements in this document to find out which element triggered the onclick event.</p>

<h1>This is a heading</h1>

<button>This is a button</button>

<p id="demo"></p>

function myFunction(event) { 
    var x = event.target;
    document.getElementById("demo").innerHTML = "Triggered by a " + x.tagName + " element";

Please tell me how do you explain this, comparing with what you told me to my function?

They are attaching the click handler to the body element, you are attaching yours to an empty div.

The w3schools example works because of event capturing / bubbling


I’m not sure I completely understand how it works for what events in what browsers.

In fact, I’m sure I don’t completely understand.

Luckily preventDefault() and stopPropagation() and the true / false argument of addEventLtstener() can help.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.