alex
alex

Reputation: 7601

How to connect a created range to the value of a textarea element?

This is how I'm setting the cursor in the first character of a textarea:

<div class="field">
  <label>Text</label>
  <textarea ref="inputEl">abc</textarea>
</div>

methods: {
  setInitialCursorPosition () {
    const inputEl = this.$refs.inputEl
    inputEl.focus()
    inputEl.setSelectionRange(0, 1)
  }
},

mounted () {
  this.setInitialCursorPosition()
}

I would like to, though share that range between methods. I checked on MDN and they say you can create a range like this:

var range = document.createRange();

range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);

However this only created a range object ... how can I connect this range to my textarea and share this range between methods?

Upvotes: 0

Views: 272

Answers (1)

Stephan-v
Stephan-v

Reputation: 20319

Why would you use a range Object for this when it's simply 2 numbers. A range object is used for something entirely different and is way more complex than what you need or should use.

https://developer.mozilla.org/en-US/docs/Web/API/Range

If you want to share your range between methods simply set an array on your data Object [0, 1] or use an Object with a min and max property if you want something more descriptive.

data() {
    return {
        range: {
           min: 0,
           max: 1
        }
    };
}

Or simply set an array, either will work.

Upvotes: 1

Related Questions