Forum Moderators: open

Message Too Old, No Replies

Alert if Click on Image

Line of code not responding

         

Jeremy_H

6:41 pm on May 8, 2006 (gmt 0)

10+ Year Member



I'm trying to get this line of code to work, but it doesn't seem to want to respond.

Am I doing something wrong?

if(document.getElementsByTagName("img").onclick){alert("Test");}

kaled

6:56 pm on May 8, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



What are you trying to do? As written, it makes no sense. You appear to be testing an array (of images) for the existence of a property called "onclick".

You could try

if(document.getElementsByTagName("img")[0].onclick) alert("Test");

This would test for the existence of an onclick event handler on the first image on the page (I think). You might need to use onClick - I can't remember.

<added>
You can also use the document.images array too, I think.
</added.

Kaled.

Fotiman

8:25 pm on May 8, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm assuming you want to attach an onclick event handler to all your images. Try this:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset:utf-8">
<title></title>
<script type="text/javascript">
function attachImgEventHandlers()
{
var imgNodes = document.getElementsByTagName("img");
for( var i = 0; i < imgNodes.length; i++ )
{
imgNodes[i].onclick = function(){alert("test");};
}
}
</script>
</head>
<body onload="attachImgEventHandlers();">
<img src="x.gif" alt="x">
<img src="y.gif" alt="y">
</body>
</html>

Jeremy_H

1:55 am on May 9, 2006 (gmt 0)

10+ Year Member



Thanks very much for the help!

Sorry for the confusion, I was trying to have the script send out an alert if any image was clicked on.

Thanks.