Search code examples
jqueryhtmlcontenteditablesummernote

Get count of current paragraph text when using Contenteditable / Summernote


trying to replicate somewhat the Medium editor.

The aim is so that the user can only have text or only have image inside a single paragraph.

When the user focus's on Summernote the insert image button is shown, as soon as they start typing it hides until they hit return and start a new paragraph and then the process starts again.

I have tested this basicly using the keyCode and checking if they are pressing keys or the return key for a new paragraph. But the issue comes when the user deletes text. If they delete (backspace) a whole paragraph's content then the insert image button should show again.

The only way I can think of is to get the current p tag that the user is editing and check its length on key up. But im having a real issue with getting that current p tag and its content. The rest is easy after that.

Any suggestions?

PSEUDO:

if ( activeParagraph.text().length) {
    showImageButton();
} else {
    hideImageButton();
}

Solution

  • Found what I needed.

    var selection = window.getSelection();
    var length = selection.anchorOffset;
    

    Running a console.log on the selection var here will give a ton of information.