Maeaex1
Maeaex1

Reputation: 755

Click button and go to page section in Vue.js

I want to implement a button that automatically scrolls to a specific div id="contactMe", which is located on the same page. I am using vue.js.

I tried the following method with native js.

    <input
        onClick="document.getElementById('contactMe').scrollIntoView();"
        type="submit"
        class="cta-button bg-yellow mt-8 flex justify-center"
        :value="$frontmatter.contactFormButton"
      />

However, I receive the following error in my console.

Uncaught TypeError: Cannot read property 'scrollIntoView' of null at HTMLInputElement.onclick ((index):1)

What is the right command in the vue framework?

Upvotes: 2

Views: 4683

Answers (2)

Kushal Suthar
Kushal Suthar

Reputation: 423

There is a package called vue-scrollto which gives you a more convenient way to handle scrolling.

new Vue({
  el: '#app',
  methods: {
  }
})
h1, button {
  margin-bottom: 1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/[email protected]/vue-scrollto.js"></script>
<div id="app">
  <button v-scroll-to="'#element'">
    Scroll to #element
  </button>
  
  <h1 id="element">Hi. I'm element</h1>
</div>

Upvotes: 0

Vucko
Vucko

Reputation: 20834

Don't use input[type="submit"] as it only should submit the form. A simple button would do with the correct Vue events:

new Vue({
  el: '#app',
  data: {
    buttonText: 'Lorem'
  },
  methods: {
    scroll() {
      const element = document.getElementById('contact-me');
      element.scrollIntoView({ behavior: 'smooth' });
    }
  }
})
body {
  background: #20262E;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

#contact-me {
  margin-top: 2000px;
  margin-bottom: 2000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button @click="scroll">{{ buttonText }}</button>
  
  <div id="contact-me">
    contact me box
  </div>
</div>

Upvotes: 7

Related Questions