简体   繁体   中英

Add event handler to element in tinyMCE

i am working on a plugin for tinymce that adds an HTML-Element to the editor content...

This is how i insert the code:

let el = tinymce.activeEditor.dom.create('div', {'class': 'css-class'}, "this is the text");
tinymce.activeEditor.selection.setNode(el);

Now i want to open a dialog if the user clicks on the new HTML-element. I tried to add an event listener like this

el.addEventListener("click", function() {
console.log("clicked!");
});

but this does not do anything...

I am working with tinyMCE 5.x

You should refer to https://www.tiny.cloud/docs/api/tinymce.dom/tinymce.dom.eventutils/#bind

From Your perspective, the code should look like this:

tinymce.activeEditor.dom.bind(el, 'click', (event) => {/* you function here */})

or

tinymce.activeEditor.dom.bind(el, 'click', function(event) {/* you function here */})

EDIT :
This is a working solution, though there should be a better way to do it

let el = tinymce.activeEditor.dom.create('div', {'class': 'css-class', 'id': "mydiv"}, "this is the text");
tinymce.activeEditor.selection.setNode(el);
tinymce.activeEditor.dom.get("mydiv").addEventListener("click", function() {
    console.log("clicked");
});

Please note that get() function from dom accepts element id without #

Here is a TinyMCE Fiddle that adds a click listener to content that exists in the editor:

https://fiddle.tiny.cloud/g9haab

I would note that you don't need to use any TinyMCE specific APIs to add a click listener - once you have content in TinyMCE it is effectively an HTML document in an iframe and you can interact with it just as you can any other HTML document. The Fiddle has some default content in the editor when it loads:

<p>
  This is a paragraph of text that 
  <span style="color: red; font-weight: bold;" id="target">
    contains a span
  </span>
   to add a click listener
</p>

...and then there is code in a setup function that looks for the <span> with the id of target and attaches a click listener using standard JavaScript:

const theTarget = editor.contentDocument.getElementById('target');
theTarget.addEventListener("click", function () {
  console.log('You CLICKED the text!');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM