javascript onclick happening on page load

12,355

Solution 1

Try this

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

Solution 2

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

If you need to pass a variable.

Solution 3

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

Solution 4

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

  <img src="yourImage.jpg"  onclick="zoom()" />
Share:
12,355
scalen121
Author by

scalen121

Updated on July 06, 2022

Comments

  • scalen121
    scalen121 almost 2 years

    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();
    
    • Charles D Pantoga
      Charles D Pantoga about 11 years
      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 D Pantoga
      Charles D Pantoga about 11 years
      document.getElementById("us").onclick = (function(){})();
  • Bohemian
    Bohemian about 11 years
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.
  • M Sach
    M Sach about 11 years
    sorry my solution did not appear as it was not properly edited with code tag