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?
The onclick is added over an image tag inside HTML. The onclick event will make our image clickable. After a user clicks on the image, you can do whatever you want, like opening a new webpage, adding animations, changing an existing image with a new one, and so on.
To handle the load event on images, you use the addEventListener() method of the image elements. You can assign an onload event handler directly using the onload attribute of the <img> element, like this: <img id="logo" src="logo.
The best way (actually the only way*) to simulate an actual click event using only CSS (rather than just hovering on an element or making an element active, where you don't have mouseUp) is to use the checkbox hack. It works by attaching a label to an <input type="checkbox"> element via the label's for="" attribute.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With