PA. PA. - 1 year ago 57
jQuery Question

how can $(this) not be the element that triggered the event in a jquery click handler?

I have a simple click handler

<h1 id="test">

$('#test').click( ev => {
var $test = $(this);

but it does not work,
is not the emitter element. If I inspect
I see a "window" (?) (??) (??!)

also, if I change my code to

var $test = $(ev.toElement);

it works perfectly.

how can this be? what is in my code that prevents jquery to correctly pass the element in

Answer Source

Arrow functions do not bind this, arguments etc. MDN.

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download