When tracking which elements were clicked e.target.id is sometimes empty
Asked Answered
S

2

5

I am trying to test the following JavaScript code, which is meant to keep track of the timing of user responses on a multiple choice survey:

document.onclick = function(e) {

    var event = e || window.event;    
    var target = e.target || e.srcElement;

    //time tracking 
    var ClickTrackDate = new Date;
    var ClickData = ""; 
    ClickData = target.id + "=" + ClickTrackDate.getUTCHours() + ":" + 
        ClickTrackDate.getUTCMinutes() + ":" +
        ClickTrackDate.getUTCSeconds() +";";

    document.getElementById("txtTest").value += ClickData;
    alert(target.id); // for testing
}

Usually target.id equals to the the id of the clicked element, as you would expect, but sometimes target.id is empty, seemingly at random, any ideas?

Streetcar answered 25/3, 2012 at 21:7 Comment(1)
You'll find usinng jquery will make this easier as it will deal with browser issues, bugs, and quirks for you.Hyetology
M
9

Probably because the element that was clicked didn't have an ID. This will happen for example if you have HTML like this:

<div id="example">This is some <b>example</b> text.</div>

and someone clicks on the boldface word "example", so that the event target will be the b element instead of the div.

You could try walking up the DOM tree until you find an element that does have an ID, something like this:

var target = e.target || e.srcElement;

while (target && !target.id) {
    target = target.parentNode;
}
// at this point target either has an ID or is null
Muir answered 25/3, 2012 at 21:35 Comment(2)
It does seem to be that - the radio buttons of the survey are inside table cells, and clicking just off the button but within the cell still selects it, but as in your example there is not an id for the table cell. Thanks!Streetcar
Had this problem, really confusing, in my case I bound to a <li> but like you say, if I click on the containing text it works but if I click in the space outside the text it gives currentTarget null... I'm just confused over all the different event member variables and how they are supposed to point I guess :)Cumuliform
O
3

just use e.currentTarget instead of e.target.

Obfuscate answered 2/12, 2018 at 16:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.