Call function when adding a div to my site
Question by ifsession
I have a script which adds a div to my site when I upload a photo. Now I wan’t to call a function when this div gets added. I’ve tried this, but it doesn’t work.
var divImg = document.createElement("div");
divImg.id = "divimg";
newImg.setAttribute('onload','urediBtnx(this)');
divImg.innerHTML = '<a href=""><img src="/imago/images/btnx.gif" class="btnx"></a>';
It should call this function:
function urediBtnx(dv){
alert("blabla");
}
The thing is, if I do it this way, then the function gets called, but I need to get the div, not the img.
divImg.innerHTML = '<a href=""><img onload="urediBtnx(this)" src="/imago/images/btnx.gif" class="btnx"></a>';
Answer by Christophe
You can attach onload event handlers to element like body, img, script or iframe, but not to a div.
In your scenario, the div is the grand-parent of your image. You can keep the onload on the image, then use this.parentNode.parentNode to reach the div.
Answer by Starx
Div does not have an onload event. They are only availabe for <body>
, <frame>
, <frameset>
, <iframe>
, <img>
, <link>
or <script>
.
Subsequently calling the function after its added to the DOM is a way.
parent.appendChild(divImg);
urediBtnx();
The possibility of a callback can be gained if you are jQuery library
$("#parent").append($(divImg), function() {
urediBtnx();
});