'Svelte access the current element on event trigger
I am having issues with accessing an element values using this keyword.
this is what I have (doesn't work)
{#if item}
<img src={'http://example.com/'+item.profile_img}
on:error={this.src='/public/unknown.svg'}
alt="user" />
{/if}
I would like to use '/public/unknown.svg' if the image doesn't exist and set the error to null.
I don't understand why the this keyword is undefined nor the normal onerror method doesn't work too.
This is the plain HTML version of what I want to achieve in svelte.
<img src="http://example.com/non-existent-image.jpg"
onerror="this.onerror=null;this.src='http://example.com/existent-image.jpg';" />
I have tried it in various ways and failed, please help.
Solution 1:[1]
use and inline function like this and get the target then set the src
{#if item}
<img src={'http://example.com/'+item.profile_img}
on:error={(e) => {
e.target.src='/public/unknown.svg'
}}
alt="user" />
{/if}
or if you prefer to use this you need to use function in order to access the correct this to the current tag
{#if item}
<img src={'http://example.com/'+item.profile_img}
on:error={function() {
this.src='/public/unknown.svg'
}}
alt="user" />
{/if}
Read more about arrow functions and this
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
