How make smooth scrolling in nuxt.js and bootstrap site?

Viewed 10022

I try make site with nuxt.js and this template. I copied folders: css, img, js, scss, vendor from template to static folder of my nuxt project. After this I maked nuxt.config.js and pages/index.vue files. All working good except smooth scrolling on page. I see error in browser console:

agency.min.js:7 Uncaught TypeError: Cannot read property 'top' of undefined
at a (agency.min.js:7)
at agency.min.js:7
at agency.min.js:7

How I can resolve this issue?

UPD: You can download this project to reproduce error

5 Answers

First, you need to overwrite the router default behavior like this. Paste this anywhere inside your nuxt.config.js:

   {
     //.......
      router: {
        scrollBehavior(to) {
          if (to.hash) {
            return window.scrollTo({
              top: document.querySelector(to.hash).offsetTop + window.innerHeight,
              behavior: 'smooth'
            })
          }
          return window.scrollTo({ top: 0, behavior: 'smooth' })
        }
      }
    }

Then your anchor link should be like this:

<nuxt-link :to="{ path: '/',hash:'#about'}">Contact</nuxt-link>

Sajjad Aljileezi's answer is valid, however, if you are looking for a simpler alternative is to add this simple line in a custom CSS file. You can import said file into your nuxt.config.js file.

html {
   scroll-behavior: smooth;
}

The nuxt.config.js file would like something like this:

css: ['~/assets/style/yourcssfile.css']

Starting from Nuxt v2.9.0, you can use a file to overwrite the router scrollBehavior. This file should be placed in ~/app/router.scrollBehavior.js (note: filename is case-sensitive if running on Windows).

Resources:

Here's an example with smooth scrolling to hash links, otherwise scrolling to top.

export default function (to, from, savedPosition) {
  if (to.hash) {
    return {
      selector: to.hash,
      behavior: 'smooth'
    }
  } else {
    return { x: 0, y: 0, behavior: 'smooth' }
  }
}

This is due to the server-side rendering, you are using something that SSR can't resolve, probably a call to window or document.

If you need to specify that you want to import a resource only on the client-side, you need to use the process.client variable.

You can check this out here : https://nuxtjs.org/faq/window-document-undefined

It seems in nuxt 2.16+ for smooth scrolling basic setup

<button @click=scrollToTop()>Jump to top of page</button>

. . .

methods: {
    scrollToTop() {
      window.scrollTo({ top: 0 });
    }
  }
Related