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?
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>
`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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With