Skip to content

Instantly share code, notes, and snippets.

@stillfinder
Created August 7, 2020 07:39
Show Gist options
  • Save stillfinder/d0e2e5df0d4ca0defefd6ea72e72523d to your computer and use it in GitHub Desktop.
Save stillfinder/d0e2e5df0d4ca0defefd6ea72e72523d to your computer and use it in GitHub Desktop.
Insert text in cursor position in textarea
<template>
<div>
<textarea ref="body" class="form-input" @input="handleInput" @click="handleInput" v-model="content"></textarea>
<div>{{ position}}</div>
<button class="button" @click="insertWtf">Insert '<-WTF->'</button>
</div>
</template>
<script>
export default {
data() {
return {
position: 0,
content: 'Just an initial content',
}
},
methods: {
handleInput(e) {
this.position = e.target.selectionStart;
},
focusBody() {
this.$refs.body.focus();
},
insertWtf() {
this.position = this.$refs.body.selectionStart;
alert('WTF');
this.$nextTick(function () {
this.$refs.body.focus();
});
this.content = this.content.substring(0, this.position) + ' WTF ' + this.content.substring(this.position);
this.$nextTick(function () {
this.$refs.body.selectionEnd = this.position;
});
}
},
mounted() {
this.position = this.$refs.body.selectionStart;
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment