Forum Moderators: open
this is my question, I wrote a script that generates new IMGs in my page. I need to add a onClick property to these newly generated images. I would like to have some javascript solution, that would work the same way like if the images would be written in HTML they had these tags: <img onClick='javascript: myFunction("thisImageId");'>
this is a part of my code:
function addNewImg(newImageId){
newImg = document.createElement('img');
newImg.id = "image"+newImageId;
newImg = document.getElementById("divimage1").appendChild(newImg);
document.getElementById("image"+newImageId).onclick=ppEdit("image"+newImageId,"image"); // this is the line that doesnt work for me
}
sorry for my english, any help will be greatly appreciated
when I use this:
function klik(){
alert("ppp");
}
function addNewImg(newImageId){
newImg = document.createElement('img');
newImg.id = "image"+newImageId;
newImg = document.getElementById("divimage1").appendChild(newImg);
newImg.onclick=klik
}
it works. The new image is created and after clicking on it "ppp" is alerted.
but when I use this:
function klik(ff){
alert(ff);
}
function addNewImg(newImageId){
newImg = document.createElement('img');
newImg.id = "image"+newImageId;
newImg = document.getElementById("divimage1").appendChild(newImg);
newImg.onclick=klik("ppp");
}
"ppp" is alerted in the moment of executing the statement newImg.onclick=klik("ppp"); and when clicking on the generated image nothing happens, even Javascript Console of Firefox stays blind.
I googled a bit and found that the first example shoul be used, but I need to use some argument to be able to edit the generated image later. And what if there will be 10 generated images?
function addNewImg(newImageId){
newImg = document.createElement('img');
newImg.id = "image"+newImageId;
newImg = document.getElementById("divimage1").appendChild(newImg);
var onC='ppEdit("image'+newImageId+'","image")';
document.getElementById("image"+newImageId).onclick=new Function(onC);
}
it works
function addNewImg(newImageId){
//object detection check
if (!document.getElementById &&!document.createElement){return;}
newImg = document.createElement('img');
newImg.id = "image"+newImageId;
newImg = document.getElementById("divimage1").appendChild(newImg);
var onC='ppEdit("image'+newImageId+'","image")';
document.getElementById("image"+newImageId).onclick=new Function(onC);
}
alternative solution:
if (!document.getElementById) {return;}
document.getElementById("image"+newImageId).onclick=function(){
ppEdit(this.id, "image");
}