Home > Mobile >  How scroll the cursor to top of textarea content with Vuejs
How scroll the cursor to top of textarea content with Vuejs

Time:06-06

I am using Vuejs 2 with vuetify.

I have a textarea and I fill your content in 'mounted'. I need scroll to top of the textarea content when I click a button. I am trying the next code, but no look.

<template>.
  <div>
     <v-btn @click.stop="testScroll">Test</v-btn>
     <v-textarea
                      ref="atend"
                      v-model="obs"
                      label="Text"
                      outlined
                      hide-details
                      rows="3"
      ></v-textarea>
</div>
</template>

<script ....
data:()=>(
{obs:null}
),
mounted(){
   this.obs="My text with ten or more  lines"
},
methods:{
testScroll() {
      const textarea = this.$refs.atend
      textarea.scrollTop = 0
      this.$refs.atend.focus()
}
}
</script>

CodePudding user response:

You can try with getElementById and setSelectionRange:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data:()=>(
    {obs:null}
  ),
  mounted(){
    this.obs = `My text with ten or more  lines
    My text with ten or more  lines
    My text with ten or more  lines
    My text with ten or more  lines
    My text with ten or more  lines
    My text with ten or more  lines
    My text with ten or more  lines
    My text with ten or more  lines
    My text with ten or more  lines`
  },
  methods:{
    testScroll(e) {
      const input = document.getElementById('doc');
      input.scrollTop = 0
      input.focus()
      input.setSelectionRange(0,0)
    }
  }
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">
<div id="app">
  <v-app>
    <v-main>
      <v-container>
        <div>
          <v-btn @click.stop="testScroll($event)">Test</v-btn>
          <v-textarea
            ref="atend"
            v-model="obs"
            label="Text"
            outlined
            hide-details
            rows="3"
            id="doc"
          ></v-textarea>
        </div>
      </v-container>
    </v-main>
  </v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>

CodePudding user response:

Try this

<v-textarea
    id="atend"
    ref="atend"
    v-model="obs"
    label="Text"
    outlined
    hide-details
    rows="3"
  ></v-textarea>


testScroll() {
   document.getElementById("atend").scrollIntoView({ block: "start" });
}
  • Related