0

I created an Image Element on we page dynamically via javaScript.
And I want to set onClick for my new created image element .

I face with an issue and I don't know why ?,

My Original Code :

<html>
<body>

<button type="button" onclick="createImgNote()">Get line height</button>

<script>

function createImgNote() { 
 var img = document.createElement('img'); 
 img.src ='ic_notebook.png'; 
 img.style.left="100px";
 img.style.top="150px";
 img.style.position = "absolute";
 img.onclick = imgClick;
 document.body.appendChild(img); 
 }

function imgClick()
{
 alert("imgClick called");
}
</script>
</body>
</html>

When I use img.onclick = createImgNote means my function without ()
Browser make image first and then each time user clicks on image, Broswer executes my onclick function.

But When I use img.onclick = createImgNote() means my onclick function with ()
Browser excutes my function first and then create image element and finally created image element is not clickable.

If any one knows this issue please tell me why this issue happen?

Alireza Bideli
  • 733
  • 2
  • 7
  • 28

1 Answers1

2

when you do img.onclick = createImgNote it assigns that function to that event listener.

When you do img.onclick = createImgNote() it calls the function and assigns the return value to that listener. anytime you follow a function with () you are calling the function.

Dave Newton
  • 152,765
  • 23
  • 240
  • 286
tstrand66
  • 775
  • 5
  • 10