scalen121
scalen121

Reputation: 925

javascript onclick happening on page load

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" />

Upvotes: 11

Views: 17248

Answers (5)

user2584621
user2584621

Reputation: 2743

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

Upvotes: 4

kravits88
kravits88

Reputation: 13049

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

If you need to pass a variable.

Upvotes: 5

M Sach
M Sach

Reputation: 34424

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

  <img src="yourImage.jpg"  onclick="zoom()" />

Upvotes: 1

Tamil Selvan C
Tamil Selvan C

Reputation: 20229

Try this

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

Upvotes: 13

xdazz
xdazz

Reputation: 160943

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

instead of

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

Upvotes: 0

Related Questions