0

I have created an image in js after clicking on a button. How do I perform an action on the image when it is clicked after it has been rendered? Here is the code I tried:

function sayhi(){

    for (var m = 0; m <animals.length;m++){
        var image = document.createElement('img');
        image.src = "animalgameback.jpg";
        image.id = animals[m];
        document.getElementById('body').appendChild(image); 
        image.onclick = flip(this);

    }
}

However when I set the onclick image attribute, it performs the task only before the image has even been rendered. Any suggestions?

Athreya Daniel
  • 101
  • 1
  • 10
  • Does this answer your question? [Why is the method executed immediately when I use setTimeout?](https://stackoverflow.com/questions/7137401/why-is-the-method-executed-immediately-when-i-use-settimeout) – Heretic Monkey Apr 02 '20 at 20:44
  • Basically, you're setting `onclick` to the result of calling `flip(this)`. You should consider using the more modern [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) method of adding event listeners rather than the old style on* properties. – Heretic Monkey Apr 02 '20 at 20:45

4 Answers4

1

you have to change the line:

image.onclick = flip(this);

to this:

image.addEventListener("click",function flip(this){ }, this);
miri
  • 26
  • 4
0

event handlers have to be a function, so :::

change this

image.onclick = flip(this);

to this

image.onclick = function(){flip(image);}
Mohammed Samir
  • 376
  • 3
  • 9
0
image.addEventListener("click", function(event) {
  flip(this) 
}, false)

Remember to not use arrow functions if you want to access this scope of a function.

0

You're not binding the function flip here to the 'click' event, but the result, or return value of the call to a function identified as flip. The this value added to the call might be window.

image.onclick = flip;

and a function like the following:

function flip (event) {
  var
    eImage = event.target;
  ...

  ...
}

might be a quick solution.

Duck
  • 76
  • 4