views:

201

answers:

2

I have a click function bound to many elements. It is possible that sometimes these elements may sit within one another. So, the click event is bound to a child and also bound to its parent. The method is specific to the element clicked. Naturally, because of event bubbling, the child's event is fired first, and then the parents. I cannot have them both called at the same time because the parents event overwrites the event of the child. So I could use event.stopPropagation() so only the first element clicked receives the event. The problem is that there are other click events also attached to the element, for example, I am using jQuery's draggable on these elements. If I stop the propagation of the click event, then draggable doesn't work, and the following click events are not called.

So my question is: Is there a way to stop the event bubbling of the method the event will call and not the entire event?

+2  A: 

try someting like this

$(mySelector).click(function(evt) {
  if (evt.target == evt.currentTarget) {
      ///run your code.  The if statment will only run this click event on the target element
      ///all other click events will still run.
  }
});
John Hartsock
I posted my reply as new answer so you can see the HTML. look below
Dale
e and evt do not match
Mark Schultheiss
@Mark, yeah. @John, some newby may spend hours on that... you may want to edit it for that sake :D
Dale
A: 

Brilliant John, but here is the prob.

<div id="Elm1"><!-- relative -->
 <div class="Elmchildren"></div><!-- absolute-->
 <div class="Elmchildren"></div><!-- absolute-->
 <div class="Elmchildren"></div><!-- absolute-->

 <div id="Elm2"><!-- relative -->
  <div class="Elmchildren"></div><!-- absolute-->
  <div class="Elmchildren"></div><!-- absolute-->
  <div class="Elmchildren"></div><!-- absolute-->
 </div>

</div>

click event is bound to #Elm1 and #Elm2. The .Elmchildren are width and height 100%. So they are actually the current targets.

Dale
Ah, so maybe detect if the parent of the e.currentTarget is e.target?
Dale
Well, I mean detect if e.currentTarget is the parent of e.target. That does the trick. Thanks, John!
Dale