0

I have an editable div and I want to insert some text when another div is clicked, using document.execCommand. When I use a button, it works properly, but it doesn't work when a clickable div is used.

<!-- When I click this, it works -->
<button on:click={e => document.execCommand("insertText", false, "Some text")}>Inser text</button>

<!-- When I click this, it doesn't -->
<div on:click={e => document.execCommand("insertText", false, "Some text")}>Inser text</div>

<div contenteditable="true" />

I suspect it's a focus issue. I have tried calling e.preventDefault() but it doesn't work either.

It's not relevant but I'm using Svelte.

Héctor
  • 24,444
  • 35
  • 132
  • 243

1 Answers1

0

I found a solution in this post.

Basically, mousedown event should be used, instead of click.

In my case, it looks like this:

<div on:mousedown={e => {
  e.preventDefault();
  document.execCommand("insertText", false, "Some text");
}>Inser text</div>
Héctor
  • 24,444
  • 35
  • 132
  • 243