2

I want to use contenteditable attribute of HTML for my component to make a area editable.

For this, I use @input directive but it does not work as I expect. I expect the caret keeps the end of the entire input value but it moves to the head position.

Animation Gif Image

enter image description here

Demo

https://codesandbox.io/s/oj9p82kvp6

Code

<template>
    <div>
        <p contenteditable="true" @input="update">{{ text }}</p>
    </div>
</template>

<script>
    export default {
        name: 'ReadWrite',
            data () {
                return {
                    text: 'edit here!'
                }
            },
        methods: {
            update (e) {
                this.text = e.target.textContent
            }
        }
    }
</script>

<style scoped>
    :read-write {
        border: solid 1px #cccccc;
        padding: 5px;
    }
</style>
shu
  • 234
  • 4
  • 15
  • This might help https://stackoverflow.com/questions/4233265/contenteditable-set-caret-at-the-end-of-the-text-cross-browser – ittus Aug 14 '18 at 01:19

1 Answers1

1

So upon checking your sandbox code.

Whenever you edit the text inside the contenteditable p tag. The cursor moves to the first position. Assuming you don't really need to always show the cursor at the bottom and just want to fix this quirk. It's 2018 yet there is not yet existing a neat way of handling this. My two cents to solve this is to use the focusout event.

You may use the focusout directive instead.

<template>
  <div>
    <p contenteditable="true" @focusout ="update">{{ text }}</p>
  </div>
</template>

<script>
export default {
  name: 'ReadWrite',
  data () {
    return {
      text: 'edit here!'
    }
  },
  methods: {
    update (e) {
      this.text = e.target.textContent
      console.log(this.text);
    }
  }
}
</script>

See it working here https://codesandbox.io/s/0o9qow6zvp

Unless you need a two way binding here, this should do the work without a lot of nitty gritty codes just for something simple

Now the value will be bind to the text variable and the cursor will not move at the first position. Hence the jankiness will be gone.

keysl
  • 2,127
  • 1
  • 12
  • 16