Dellirium
Dellirium

Reputation: 1516

Firefox event.target issue

Generally speaking, and if I recall correctly I've used this at least a dozen times before, but for some god-forsaken reason it doesn't work since this morning... Somebody have a clue?

JSFiddle Example

HTML:

<button id="testID" onclick="foo()">
test me
</button>

<button id="testID2" onclick="foo(this)">
test me 2
</button>

JS:

function foo(event){
alert(event.target.id);
}

Upvotes: 0

Views: 52

Answers (1)

Quentin
Quentin

Reputation: 943230

In the first example, you pass undefined to event. In the second example, you pass the button to event.

If you want the event object, then you have to pass the event object. That's called event, but I don't know how standard it is for it to be created for intrinsic event attributes.

In general, you are better off binding your event handlers with JavaScript.

function foo(event){
    alert(event.target.id);
}

var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener("click", foo); 
}
<button id="testID">
test me
</button>

<button id="testID2">
test me 2
</button>

Upvotes: 1

Related Questions