I'm new to JavaScript, so this may be basic...
I'm trying to create an image dynamically and add it a event listener for "onclick". I add this img
to a div
.
I create the img like this:
function createNewSmiley()
{
var newSmiley = document.createElement("img");
newSmiley.src = "./smiley.jpg";
newSmiley.alt = "Smiley Image";
newSmiley.style.width = "64px";
newSmiley.style.height = "64px";
return newSmiley;
}
And then I add it to the div like using like this:
function positionNewSmiley(parent, smiley, x, y)
{
var newSmiley = createNewSmiley();
newSmiley.style.top = y + "px";
newSmiley.style.left = x + "px";
parent.appendChild(newSmiley);
}
And this is my main function:
function main(smileyCount)
{
var myDiv = document.getElementById("myDiv");
for (var i = 0; i < smileyCount;i++)
{
var x = Math.floor((Math.random() * 500));
var y = Math.floor((Math.random() * 500));
var smiley = createNewSmiley();
smiley.onclick = smileyClicked;
positionNewSmiley(myDiv, smiley, x, y);
}
}
function smileyClicked(ev) {
alert("OK");
}
But the onclick
event will not fire!
however, if I add the event listener to the div - it will.
What am I doing wrong?
if you add the on click within the create function it will work
function createNewSmiley()
{
var newSmiley = document.createElement("img");
newSmiley.src = "./smiley.jpg";
newSmiley.alt = "Smiley Image";
newSmiley.style.width = "64px";
newSmiley.style.height = "64px";
newSmiley.addEventListener("click", smileyClicked);
return newSmiley;
}
As mentioned in the above comment you're creating new smiley
in the positionNewSmiley
when you've to position the passed smiley
instead :
var smiley = createNewSmiley();
smiley.onclick = smileyClicked;
positionNewSmiley(myDiv, smiley, x, y);
_________________________^^^^^^
Just use it in the position function :
function positionNewSmiley(parent, smiley, x, y)
{
smiley.style.top = y + "px";
smiley.style.left = x + "px";
parent.appendChild(smiley);
}
Hope this helps.
function createNewSmiley() { var newSmiley = document.createElement("img"); newSmiley.src = "http://cfile24.uf.tistory.com/image/163BB51F4BF9DF7431AB10"; newSmiley.alt = "Smiley Image"; newSmiley.style.width = "64px"; newSmiley.style.height = "64px"; return newSmiley; } function positionNewSmiley(parent, smiley, x, y) { smiley.style.top = y + "px"; smiley.style.left = x + "px"; parent.appendChild(smiley); } function main(smileyCount) { var myDiv = document.getElementById("myDiv"); for (var i = 0; i < smileyCount;i++) { var x = Math.floor((Math.random() * 500)); var y = Math.floor((Math.random() * 500)); var smiley = createNewSmiley(); smiley.onclick = smileyClicked; positionNewSmiley(myDiv, smiley, x, y); } } function smileyClicked(ev) { alert("OK"); } main(6);
<div id='myDiv'></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.