Question

I have an editable element inside a div which itself is clickable. Whenever I click the x-editable anchor element, the click bubbles up the DOM and triggers a click on the parent div. How can I prevent that? I know it's possible to stop this with jQuery's stopPropagation() but where would I call this method?

Here's the JSFiddle with the problem: http://jsfiddle.net/4RZvV/ . To replicate click on the editable values and you'll see that the containing div will catch a click event. This also happens when I click anywhere on the x-editable popup and I'd like to prevent that as well.

EDIT after lightswitch05 answer

I have multiple dynamic DIVs which should be selectable so I couldn't use a global variable. I added an attribute to the .editable-click anchors which get's changed instead.

editable-active is used to know if the popup is open or not

editable-activateable is used instead to know if that .editable-click anchor should be treated like it is

$(document).on('shown', "a.editable-click[editable-activateable]", function(e, reason) {
  return $(this).attr("editable-active", true);
});

$(document).on('hidden', "a.editable-click[editable-activateable]", function(e, reason) {
  return $(this).removeAttr("editable-active");
});

The check is pretty much like you've described it

$(document).on("click", ".version", function() {
  $this = $(this)

  // Check that the xeditable popup is not open
  if($this.find("a[editable-active]").length === 0) { // means that editable popup is not open so we can do the stuff
    // ... do stuff ...
  }
})
Was it helpful?

Solution

For the click on the links, simply catch the click event and stop it:

$("a.editable-click").click(function(e){
    e.stopPropagation();
});

The clicks within X-editable are a bit trickier. One way is to save a flag on weather the X-editable window is open or not, and only take action if X-editable is closed

var editableActive = false;

$("a.editable-click").on('shown', function(e, reason) {
    editableActive = true;
});

$("a.editable-click").on('hidden', function(e, reason) {
    editableActive = false;
});

$("div.version").click(function(e) {
  var $this;
  $this = $(this);
  if(editableActive === false){
      if ($this.hasClass("selected")) {
        $(this).removeClass("selected");
      } else {
        $(this).addClass("selected");
      }
  }
});

Fixed Fiddle

OTHER TIPS

It's not pretty, but we solved this problem with something like:

$('.some-class').click(function(event) {
  if(event.target.tagName === "A" || event.target.tagName === "INPUT" || event.target.tagName === "BUTTON"){
    return;
  }

We're still looking for a solution that doesn't require a specific list of tagNames that are okay to click on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top