I dynamically create DOM elements based upon the user input using this code (Example 1). I also use php/xhtml to create the same elements on a reload (Example 2).
Problem I’m seeing is that my image onerror event only works for the reloaded version. Here I use traditional inline event registration to i_bm_err and it works.
However for the javascript version, the onerorr callback method does not fire.
My questions: Do I need to add an event Listener? If so, what is the event listener’s type? I have tried adding event listeners of type “error” and “onerror”, but this did not work. This makes me think that maybe adding and evernt listener is not the issue.
Example 1
function o3(a)
{
return document.createElement(a);
}
var b=o3('a');
b.innerHTML=c[1].value;
b.href=c[2].value;
b.name="a1";
b.className="b";
b.target="_blank";
var e=o3('img');
e.className="c";
e.name="bo_im";
e.src=b.href+'favicon.ico';
e.onerror=function(e){e.src='http://www.archemarks.com/favicon1.ico';};
Example 2
PHP / XHTML
function bookmarks()
{
$email = $_SESSION['email'];
$query_return = database::query("SELECT * FROM bo WHERE email='$email' ORDER BY name ASC");
while ($ass_array = mysqli_fetch_assoc($query_return))
{
$fav=$this->fav($ass_array['url']);
echo "<img name=\"bo_im\" class=\"c\" src=\"$fav\"/ onerror=\"i_bm_err(this)\"><a target=\"_blank\" name = \"a1\" class = \"b\" href = \"$ass_array[url]\">$ass_array[name]</a>";
}
}
Javascript
function i_bm_err(a)
{
a.src='http://www.archemarks.com/favicon1.ico';
}
Research:
MDN – element.addEventListener
In the example above, the value of this within modifyText() when
called from the click event is a reference to the table ‘t’. This is
in contrast to the behavior that occurs if the handler is added in the
HTML source:
As @Paul Grime mentioned, you need to attach all your events (error, load etc) prior to setting the src attribute.