Veeru
Veeru

Reputation: 4936

Image url, separate click events for a, img

If i have this html

<a>
<img style="display: block; width: 15px;" src="icon-07.png" alt="facebook" width="21" border="0">
</a>

is it possible to create click events for img with out trigger click on "a" and vice versa?

I need to do two separate handlers, if the user clicks on image provide an interface to change the image, and a click on "a" should provide an interface to change the URL.

clicks on img are taking precedence when i use

$(*div*).on("mouseup",'a', function(e)){}
$(*div*).on("mouseup",'img', function(e)){}

Really looking forward to your expert advice.

Regards

Upvotes: 2

Views: 52

Answers (2)

31piy
31piy

Reputation: 23859

To prevent the click event from bubbling up, you can use stopPropagation:

$(*div*).on("mouseup",'img', function(e) {
  e.stopPropagation();
  // do your stuff here
})

Not sure what do you mean by vice-versa. You have only one element under a. So, user will have to click on the img, and not on the a alone.

Upvotes: 1

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48357

Yes, you have to pass the event as argument and use stopPropagation function.

$('div').on("mouseup",'img', function(e){
    e.stopPropagation();
})

This behaviour is called bubbling. When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.

Upvotes: 3

Related Questions