4
<a class="lnk" href="#" onclick="showItem();">
    <span data-id="27">TEST</span>
</a>

function showItem()
{
    var itid = event.target.dataset.id;
    alert(itid);
}

If you try this jsfiddle code you can see that with IE (11) and Chrome the event object is correctly evaluated, but with Firefox (32.0) you get an error (ReferenceError : event is not defined)

It's a bug of Firefox or a different event object lifecycle in IE and Chrome ? However since in IE and Chrome it's working I think it's a problem. About a workaround ?

p.s: in jsfiddle, only with firefox, code selection still having problem (after some run you cannot select code.

Luca
  • 1,588
  • 2
  • 22
  • 26

1 Answers1

16

You should pass event as an argument to the function:

<a class="lnk" href="#" onclick="showItem(event);">
    <span data-id="27">TEST</span>
</a>

function showItem(e)
{
    e = e || window.event;
    var itid = e.target.dataset.id;
    alert(itid);
}

Accessing it as a global variable is an IE feature that Chrome copied, but I don't think it's standard Javascript.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • ok works, but part of the question is : why in IE and Chrome works without passing the event ? they implicitly pass it ? – Luca Sep 10 '14 at 21:47
  • 1
    They have a global variable that gets set to the current event. – Barmar Sep 10 '14 at 21:48
  • ok, the answer at that part of the question is here http://stackoverflow.com/questions/7457260/event-target-not-working-on-firefox – Luca Sep 10 '14 at 21:49
  • Right. This answer won't work in IE. That question shows the correct code for all browsers. – Barmar Sep 10 '14 at 21:50