Reputation: 2166
I have a small on load script to set some classes that looks like this:
function frameIt() {
console.log("called frameit")
$( 'img' ).on('load', () => {
console.log("running listener")
debugger;
$( this ).addClass( "tasty" );
});
console.log("set listener")
}
My issue is that $(this)
is always set to the window
even though this
in the context is the loaded img
tag as Chrome's debugger shows. Any ideas for why this is happening? Here's a Chrome debugger screenshot:
Upvotes: 0
Views: 86
Reputation: 57964
It's because arrow functions don't bind their own this
context -- they take the this
value of the enclosing scope. Since jQuery binds an event handler's this
internally, but this
cannot be bound to an arrow function, this
refers to window
as it is the this
value of the enclosing scope. Use a regular function instead.
Upvotes: 6
Reputation: 21
$( 'img' ).on('load', function () {
console.log("running listener")
debugger;
$( this ).addClass( "tasty" );
});
Upvotes: 2