Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the element from a jQuery on() event using an ES6 arrow function? [duplicate]

Previous to using ES6 arrow functions, if I wanted to get the element from a jQuery on() click event then I could do something like this:

$(document).on('click', '.inserted-el', function(event) {
    console.log(this);
});

However, with the arrow function, I can no longer access this in that way. How do I get hold of the element that was clicked on?

like image 793
Fisu Avatar asked Mar 17 '16 08:03

Fisu


2 Answers

You can use event.currentTarget to refer to the target element of the handler

$(document).on('click', '.inserted-el', function(event) {
  snippet.log('old -> ' + this.innerHTML + ':' + event.currentTarget.innerHTML);
});
$(document).on('click', '.inserted-el', (event) => {
  snippet.log('new -> ' + this.innerHTML + ':' + event.currentTarget.innerHTML);
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="inserted-el">1</button>
<button class="inserted-el">2</button>
like image 166
Arun P Johny Avatar answered Sep 17 '22 22:09

Arun P Johny


`event.currentTarget` 

is your friend here.

The reason you can't access it as 'this' is because arrow functions have the same 'this' as their parent scope.

You should also know about event.target

http://joequery.me/code/event-target-vs-event-currenttarget-30-seconds/

like image 35
Tom Avatar answered Sep 20 '22 22:09

Tom