Search code examples
javascripteventswebweb-deploymentonerror

onerror Event didn`t work


I try create code which replace src image on another. I want to use function invalidUrl():

function invalidUrl() {
    paint.src = randomvariable;
}

but this function isn`t running :<

var paint = '<img src="' + url + '"class="heightImg" onerror="invalidUrl()"/>' + '</br></br>' + description;

How to change src images if current picture doesn`t exist?


Solution

  • paint.src // undefined
    

    this is because paint is of "string" type and strings have no "src" property.

    You can use vanilla JavaScript to build your img element:

    var paintedElement = document.createElement("img");
    paintedElement.src = url;
    paintedElement.class = "heightImg";
    paintedElement.onerror = function invalidUrl() { 
         paint.src = randomvariable;
    };
    paintedElement.innerHTML = "</br></br>" + description;
    // append where you need to append paintedElement