1

I am writing a HTML editor, anyone can plug this plugin into their site and make use of it.

Plugin Usage

$(".editable").htmleditor();

Onclick on this elements I will change the element into contenteditable and my editor menu will be opened near the element like aloha editor.

Problem

Scenario 1

<div class='editable' onclick='loadUrl('https://facebook.com')'>
</div>

Scenario 2

<div class='editable' id='openNewWindow'></div>
<script>
    $("#openNewWindow").click(function(e){
        e.preventDefault();
        e.stopPropagation();
    });
</script>

Aforementioned scenarios I won't receive the event. It makes my plugin not reliable. I tried couple of solutions.

Solutions I tried

  1. Removed all elements in a body and reinserted into it again to remove attached event handlers. It works but the UI is distorted while inserting in some sites.

  2. Added onclick='return false' attribute in all elements. It works for some elements only.

How to unbind all attached event handlers and prevent the default event of an element?

john.ab
  • 53
  • 1
  • 6

1 Answers1

0

In Scenario 1, the user of your plugin has both made an element editable, and also made clicking on it navigate away from the current page. That doesn't make much sense, but it's their business. In this situation they can't realistically expect your plugin to run.

In Scenario 2, you need to process the click event before it's handled elsewhere. Removing or suppressing existing handlers is not a good idea: it may make other parts of the page fail, and is annoying to your users in any case.

Instead, you can make your handler run in the event capture phase like this:

editableElement.addEventLister("click", myHandler, true); // note the "true"

Now your handler will run before all handlers added using JQuery (and most handlers that people add via any means), which run in the event bubble phase. Note that this technique only works in modern browsers (i.e., not IE < 9).

For reference: What is event bubbling and capturing?

Community
  • 1
  • 1
radiaph
  • 4,001
  • 1
  • 16
  • 19