0

How would one scroll to an element in a webpage using javascript? I want to basically create the same thing that happens when using <a href="#link"></a> but in javascript using a function. I do not want to use any jQuery, I'm currently using VueJS with the Vuetify framework. My navigation looks like this:

<v-navigation-drawer
  persistent
  :mini-variant="miniVariant"
  :clipped="clipped"
  v-model="drawer"
  enable-resize-watcher
  fixed
  app
>
  <v-list>
    <v-list-tile
      value="true"
      v-for="(item, i) in items"
      :key="i"
      @click="navigate(item.link)"
    >
      <v-list-tile-action>
        <v-icon>{{ item.icon }}</v-icon>
      </v-list-tile-action>

      <v-list-tile-content>
        <v-list-tile-title>{{ item.title }}</v-list-tile-title>
      </v-list-tile-content>
    </v-list-tile>
  </v-list>
</v-navigation-drawer>

As you can see, I have a @click property already set up, but I have no idea how to actually scroll to an ID link like #info or #contact

1
  • You can use scrollTo Commented Sep 26, 2018 at 4:38

3 Answers 3

1
document.getElementById('idhere').scrollIntoView();
Sign up to request clarification or add additional context in comments.

3 Comments

Could you please add some details to your answer?
suppose you having a div as below <div id="div1">Scroll to here </div> and a button <button onclick="scrollTo()">
The scrollTo() will have document.getElementById('div1').scrollIntoView(); This is pure js
1

I would be careful using scrollIntoView as it doesn't work on all browsers. From the MDN web docs..

This is an experimental technology Check the Browser compatibility table carefully before using this in production.

I suggest using a lightweight scroll script such as smooth-scroll

Comments

0

If you have the element you can use scrollIntoView. With scrollIntoViewOptions it allows a smooth scroll too.

e.g. document.querySelector(item.link).scrollIntoView();

It should be noted however, that as you are replicating default behaviour it is always advisable to use native elements and default behaviour when ever possible for accessibility proposes. This provides interactions that are known and expected by the user, as with custom implementations often certain benefits are lost, e.g. keyboard interaction or screen reader quick actions

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.