11

I'm trying to make a simple Javascript function to open a window with a bigger image when an image is clicked on. What happens is this test alert pops up on the page load and then does nothing when i click on the image. Here is the code

function zoom() {
  alert("test!");
}
document.getElementById("us").onclick = zoom();
<img id="us" src="http://placekitten.com/200/200" />

2
  • 5
    When you add the '()' you're calling the function. What you want to do is reference the function. What you posted is the equiv of writing an anonymous function like so:
    – Charles
    Apr 28, 2013 at 2:45
  • document.getElementById("us").onclick = (function(){})();
    – Charles
    Apr 28, 2013 at 2:45

5 Answers 5

13

Try this

function zoom()
{
    alert("test!");
}
document.getElementById("us").onclick=zoom;
0
5
function zoom()
{
    alert("test!");
}
document.getElementById("us").onclick=function(){zoom(variable1)};

If you need to pass a variable.

4

for es6 onclick = () => zoom(i) works

1

why not bind the onclick with html element itself instead of doing it in javascript

  <img src="yourImage.jpg"  onclick="zoom()" />
2
  • 1
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.
    – Bohemian
    Apr 28, 2013 at 2:51
  • sorry my solution did not appear as it was not properly edited with code tag
    – M Sach
    Apr 28, 2013 at 2:53
0
document.getElementById("us").onclick=zoom;

instead of

document.getElementById("us").onclick=zoom();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.