I am changing the src
attribute of an image element. If there's an error I want to know the error status code.
You could adapt this source example on mdn web docs. If you change the src
attribute programmatically and need to check first if it gives an error code, it could do the job. Here a draft, I hope this is going to help you.
let changesrc = (newsrc) => {
const myImage = document.getElementById('testimg');
const myRequest = new Request(newsrc);
fetch(myRequest).then((response) => {
console.log(response.status);
if(response.status == "200") {
response.blob().then((myBlob) => {
const objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
}
});
};
<button onclick="changesrc('https://picsum.photos/200');">test ok</button>
<button onclick="changesrc('https://picsum.photos/noway');">test not ok</button>
<img id='testimg' src="https://picsum.photos/200">