Click here to Skip to main content
15,896,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
HI, all

i have a img on my form and set img on click and call java-script function. it works fine on all images but on some images i don't have the src ..and i set the background image on outer div. now when i click on such images the on click is not working at all. can some one help me ?


HTML
<div id="imgcontent">
<div id="imgdiv1">
<img src="abc.png" alt=""  önclick="changedata();"/>
</div>

<div id="imgdiv2">
<img src="" alt=""  önclick="changedata();"/>
</div>
</div>


JavaScript
function changedata()
{
alert('hello');
}


now for the first image this will work but for second img where we don't have img or alt="" this will not work. also on second image i have set background image = noimage.png on the imgdiv2.
Posted
Updated 26-Mar-14 1:43am
v2
Comments
Snesh Prajapati 26-Mar-14 7:33am    
Can you write code? It will help to identify the problem.
ravikhoda 26-Mar-14 7:44am    
please check the question again i improve it now ....all code is not written as it contains some database operation but this will give you some general idea.

1 solution

If you don't have src for the image and you have not defined any width or height to the image, then the image will not be displayed at all. Its size will be 0px in the browser window. Then how can you say that you clicked on this image? In such cases, you are actually clicking on the parent element and not the image.

Give width and heigh to the image and the click event will work. Here is a working example:

XML
<html>
<head>
<script type="text/javascript">
function changedata()
{
    alert('hello');
}
</script>
</head>
<body>
<div id="imgdiv2">
<img src="" alt="" onclick="changedata();" style="width:100px;height:100px;" />
</div>
</div>
</body>
</html>
 
Share this answer
 
Comments
ravikhoda 26-Mar-14 8:15am    
well i said that we add some background image on imgdiv2 with noimage.png. but i think you are right. this will work thanks.
Code Help 2014 26-Mar-14 8:20am    
If the <div> contains only this image, you can also try by adding the onclick event to the <div> instead of the <img>.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900