0

Validating image url.

I'm creating all image elements using js dynamically but some users don't have avatar in their profile. It makes code look bad. how can I know if given image-url is pointing to valid image? If someone has no avatar I can add a default avatar. but I can't determine if user really has avatar or not. code link 🔗 : https://code.sololearn.com/WuIQEt1QZlGJ/?ref=app Thanks!

22nd Dec 2019, 4:00 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
1 Odpowiedź
+ 2
Thanks! 「HAPPY TO HELP」 It's working perfectly. I would like to add one more point for future reference of others who will search for similar queries. I found on SO https://stackoverflow.com/questions/8124866/how-does-one-use-the-onerror-attribute-of-an-img-element It's necessary to nullify onerror event once it's fired. Otherwise if browser gets error for second time it'll call the same method again and again resulting in infinite iterations. here is how we can prevent this from happening. let avt=new Image('100px','100px'); avt.onerror=()=>{ avt.onerror=null; avt.src="https://www.sololearn.com/Images/NoAvatar.jpg"; /*above is default image*/ }
22nd Dec 2019, 4:42 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar