Funktion Funktion - 10 months ago 100
Javascript Question

Prevent Wordpress TinyMCE from deleting div on backspace

I'm writing a little plugin that adds grid rows and columns inside tinymce.
It works more or less correctly, but TinyMCE insists on deleting a div when it's empty. I want my columns and rows to only be deleted via a button control.

I found another question on SO that asks this and an answer that seems on the right lines, but doesn't quite work.

editor.on("keydown",function(e) {
if (e.keyCode == 8 || e.keyCode == 46) {

try {
var elem = editor.selection.getNode();

if (elem.classList.contains("columns") || elem.classList.contains("column") || elem.classList.contains("row")) {
if (elem.textContent.length == 0) {
console.log('no content');
return false;
} catch (e) {}

It doesn't work. If I change the elem.textContent.length to == 1. It does prevent the last character from deleting, but if I leave it as 0 it deletes the column/row and doesn't even reach the console.log.

The answer seems very, very close, but just out of reach.

Any ideas of how to remedy it would be greatly appreciated.


After much fiddling, I managed to get it to work by tweaking the above code.

if (elem.textContent.length <= 1) {

I think the problem is that setting textContent.length to 0 is too late, so I needed to find a way to target the delete/backspace when there's 1 character. So I'm essentially preventing the usual delete and simulating delete by adding empty contents.