views:

66

answers:

3

If I insert an image inside an <a> tag, how could I avoid, using js if it was necessary, that when someone clicks on that image it doesn't follow the link.

+3  A: 

You need to handle the <img>'s click event and return false;.

For example:

<img src="..." href="..." onclick="return false;" />

Or, using jQuery:

$('a.SomeClass img').click(function() { return false; });

However, the best solution is to move the <img> outside the <a> tag.

SLaks
A: 

Just to add to other answers on this page: you should style an anchor tag with a background image using css instead of using an image tag eg

{background: transparent url('images/myimage.png') width:20px height:20px}
James Westgate
A: 

you can also do it by event handling:

$('a.SomeClass img').click(function(event) { 
   event.preventDefault(); 
   return false;
 });

the 'event' object is automatically passed in the 'click' event handler in jQuery. Note that preventDefault() is a native javascript call on the event object, so it can be used w/o jQuery as well.

Mike Taylor