Search code examples
javascriptattributesappendchild

appendChild of objects containing javascript attributes


i have this Javascript function

function webit(thumb){
    webi = document.createElement("img");
    webi.alt=thumb.id.replace("t", "");
    webi.id = "w"+webi.alt;
    webi.className = "web";
    webi.src= thumb.src.replace("thm","web");
    webi.height=233;
    webi.onclick='alert()';
    document.body.appendChild(webi);
}

which is supposed to embed a larger version of a thumbnail image the end of the document. It works fine except that any javascript function ( ie onXXX) stays resolutely null. This seems to be no matter which JS function i use and afaict any thing i try to set it to.

The above example uses

    webi.onclick='alert()';

which fails leaving onclick null, though all the other statements succeed.


Solution

  • When in javascript the .onclick property expects a function not a string

    webi.onclick=function(){ alert(); };
    

    You could also use the addEventListener method to set an event handler

    webi.addEventListener("click",function(){ alert(); });