Listening for click event within CKEditor 4

2.5k Views Asked by At

I've been reading about how to listen for click events within the CKEditor, specifically: CKEditor's click event not firing which was answered by Reinmar, but I still can't get this working.

My scenario is I have a CKEditor instance. Paragraphs are enclosed with <p> tags, but I enclose parts of the text within <span> tags, the content looks like:

<p>This is the first paragraph</p>
<p>This is <span>The second paragraph</span></p>

I want to add a click event, so whenever a user clicks on the text within a span tag, it performs an action, I'm happy with just getting an alert to display for the time being.

This is my code that I've been trying. I've been working through the documentation on the editable() element, editor and document properties / methods.

_instance.on('contentDom', function () {

    let editable = _instance.editable();
    let elements = new CKEDITOR.dom.element(editable.getElementsByTag('span'));
    console.log(elements);

    editable.attachListener(elements, 'click', function () {
        alert('test');
        console.log("click event");
    });
});

The results of the console.log(elements) correctly logs the following:

console log result

and from reading the documentation, the attachListener() method requires the first argument to be an instance of CKEDITOR.dom.element, so I'm passing the correct arguments, but nothing is alerted or logged when I click on the span tags.

I'm not sure how to proceed to any help would be appreciated.

Edit

If I replace editable.attachListener(elements...) with editable.attachListener(editable...) it works as expected, but works whenever I click anywhere within the editor, not specifically span tags, which doesn't really help me that much.

1

There are 1 best solutions below

0
On

By default in current versions of CKEditor span's are not in the allowedContent config, so it might be stripped after you output those elements. I have a simple example here where i output the element name of the clicked element within the editor:

var editor = CKEDITOR.replace("txtarea");
editor.on("instanceReady", function(evt) {
  evt.editor.editable().on('click', function (event) {
      // YOUR CODE GOES HERE
      console.log("element clicked: ", event.data.$.target);
  });
});

If i switch to source and add span and then jump out of source again it is being stripped!

See full example here: http://run.plnkr.co/paYzYa25kt6wFM1J/