0

I have a function that shows an image based on the user input by modifying the URL. When that image isn't found the console throws a 404 error.

What I'am trying to do is :

If that error happens , I want to write "Sorry , we could not find a company with that name" but what I did doesn't seem to work because my IF statement might be wrong , but I dont know what element I should be comparing the error 404 to???

This is Javascript :


let companyImageLink = document.getElementById("companyImage");

function changeLogoImage(str)
{ 
    companyImageLink.src = "https://logo.clearbit.com/" + str + ".com"

    if (companyImageLink.src === 404 || companyImageLink.src === 404 )
        return searchedName.innerHTML = "Sorry , we could not find a company with that name"
}

This is HTML :

    <div id="companyLogo" style="visibility : hidden;">
        <div id="companyName" style="font-size: xx-large;"></div>
        <div><img src="" style="height: 120px; width: 120px;" id="companyImage"></div>
    </div>


izzypt
  • 170
  • 2
  • 16
  • 1
    `src` of an image element is not populated with the 404 status code. You've to add an error listener to the image element, see https://stackoverflow.com/questions/9815762/detect-when-an-image-fails-to-load-in-javascript . It's also possible to make an AJAX head request to the server to check the image exists. This works reliably for the images stored in your own server only. – Teemu Mar 17 '21 at 18:14
  • OK , thank you @Teemu. I did what you said , and it does seems to work... this is the code change : function changeLogoImage(str) { companyImageLink.src = "https://logo.clearbit.com/" + str + ".com" companyImageLink.addEventListener("error" , function (){ searchedName.innerHTML = "Sorry, we could not find a company with that name" }) } – izzypt Mar 17 '21 at 18:20

1 Answers1

0

I took Teemu advice and I added a error EventListener to the image element , which does what I intended in the first place.

For anyone else with some issue, those are the code changes :

let companyImageLink = document.getElementById("companyImage");

function changeLogoImage(str)
{ 
    
    companyImageLink.src = "https://logo.clearbit.com/" + str + ".com"
    
    companyImageLink.addEventListener("error" , function ()
{ 
        searchedName.innerHTML = "Sorry, we could not find  a company with that name"
     })
}


izzypt
  • 170
  • 2
  • 16