How do I add a .click() event to an image?
Enclose <img>
in <a>
tag.
<a href="http://www.google.com.pk"><img src="smiley.gif"></a>
it will open link on same tab, and if you want to open link on new tab then use target="_blank"
<a href="http://www.google.com.pk" target="_blank"><img src="smiley.gif"></a>
You can't bind an event to the element before it exists, so you should do it in the onload
event:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
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 id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
</body>
</html>
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.