How do I add a .click() event to an image?

SS' picture SS' · Sep 10, 2011 · Viewed 203.6k times · Source

I have a script that places an image based on a mouse click thanks to Jose Faeti. Now I need help adding a .click() event to the code below so that when a user clicks the image it performs the function shown in the script.

<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()

I put the entire code below, in case you want to see it.

<html>
<head>
 <script language="javascript" type="text/javascript">
 <!--

 document.getElementById('foo').addEventListener('click', function (e) {

var img = document.createElement('img');

img.setAttribute('src', 'http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png');

e.target.appendChild(img);
});

  // -->
 </script>

</head>

<body>
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()
</body>
</html>

Help?

Answer

mpen picture mpen · Sep 10, 2011

First of all, this line

<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()

You're mixing HTML and JavaScript. It doesn't work like that. Get rid of the .click() there.

If you read the JavaScript you've got there, document.getElementById('foo') it's looking for an HTML element with an ID of foo. You don't have one. Give your image that ID:

<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />

Alternatively, you could throw the JS in a function and put an onclick in your HTML:

<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" onclick="myfunction()" />

I suggest you do some reading up on JavaScript and HTML though.


The others are right about needing to move the <img> above the JS click binding too.