Home > OS >  insert bold tag in cursor position of div contenteditable
insert bold tag in cursor position of div contenteditable

Time:08-28

i have a content editable div and an event that fires everytime i enter "@" to mention a person when i chose the tagged person from a drop down i auto complete the fullname in the value of the div at the carret position, i wanted to add it inside a tag but after i do it sticks to writing in bold. how can i go back to writing normal after inserting the node

here is the function that inserts the tag :

 insertTagInDiv(val: string): void {
    const range = window.getSelection()?.getRangeAt(0);
    const newElement = document.createElement("b");
    newElement.innerHTML = val;
    range?.deleteContents();
    range?.insertNode(newElement);
  }

the template is pretty simple :

 <div >
    <div
      ref="roomTextarea"
      
      contenteditable
      data-test="chat-text-area"
      @input="onInput"
    ></div>
    <OperationChatUserTagPanel
      ref="userTagList"
      :current-taggable-user="currentTaggableUser"
      :is-tagging="isTaggingUser"
      :last-at-coordinates="lastAtCoordinates"
      :message="message"
      :taggable-users="getTaggableUserList"
      @set-tag-user="setActive"
      @tag-user="tagUser"
    />
    <div >
      <div
        
        data-test="send-message-button"
        @click="sendMessage"
      >
        Envoyer
      </div>
    </div>
  </div

and the function that tags (which i want to insert the styled tag in the editable div is :

 tagUser(id: string): void {
    const user = this.chatMembers.find(
      (member) => member.id === id
    ) as TaggableUser;
    const remainingChunkAfterCurrentTag = this.message.slice(
      this.getCaretCharOffset(),
      this.message.length
    );

    this.message =
      this.message.substring(0, this.lastAtIndex)  
      `@${user.firstName} ${user.lastName} ${remainingChunkAfterCurrentTag} `;
    this.getTextareaRef.innerText = this.message;
    this.setCaretPosition();
    this.taggingUser = false;
  }

CodePudding user response:

I think the key to understanding your issue is the fact that you're inserting text into a contenteditable div. They're honestly pretty tricky to work with and not what I expected when reading your original question. This is the solution I came up with: codesandbox.

The codesandbox is a much simplified version of your code, just concentrating on inserting bold text into a contenteditable div with other text still using normal font styling.

The key was to isolate the inserted text from the rest of the div by putting it inside it's own div with contenteditable=false. I also had to make sure it stayed inline with the rest of the text using display: inline-block. This solution may need more work in order to match 100% of your specific application's requirements but should hopefully help you get close to your desired functionality.

  • Related