Question: How can I call a JavaScript function when the user clicks on an image?
My first guess was to add an onClick
event handler to the image tag, as follows:
<img src=image.gif onClick="myFunction ();">
Unfortunately, it didn't work, so I consulted the latest JavaScript documentation (revision 3.0) on the subject. This is what Netscape Communications had to say:
Image objects do not have onClick, onMouseOut, and onMouseOver event handlers. However, if you define an Area object for the image or place the <IMG> tag within a Link object, you can use the Area or Link object's event handlers.Turning an image into a hyperlink is a simple matter; we do so as follows:
Now, however, the original question becomes a little more general:<a href=
DocumentURL>
ImageURL
<img src=>
</a>
javascript
" and a colon. After the colon, you can insert as many JavaScript commands as you like.
For example, suppose we have an image called face.jpg, and we want to pop up a JavaScript alert box when the user clicks on it. We can accomplish this with the following HTML/JavaScript code:
Go ahead, give it a try:
If you don't like the hyperlink border around the image, don't forget to include "border=0
" in the image tag.
It's also possible to have different JavaScipt commands executed when different areas of the image are clicked. This can be accomplished by using client-side image maps and supplying a different JavaScript URLs for each area in the map. More information about client-side image mapping can be found on Netscape Communication's web site.
Charlton Rose
November 23, 1996