Taha

Disable Page Scrolling When a Component Is Shown

Components like modal boxes, confirmation dialogs, or walkthrough tooltips often require the page scrolling to be disabled while they are open.

You can do that simply by setting the overflow of the <body> tag to hidden. But how can we make this behavior reusable for any component we want?

The answer, like in most cases, is to create a mixin for that. Let's call it noScrollMixin.

Creating the noScrollMixin

In your mixins directory, create a new file called noScrollMixin.js, then put this into it:

export default {
  mounted() {
    document.body.classList.add('no-scroll')
  },

  destroyed() {
    document.body.classList.remove('no-scroll')
  }
}

The basic job of this mixin is to add no-scroll class to the <body> tag whenever the component is created and displayed. This class remains until the component is destroyed and removed from the DOM.

Let's write the css for the .no-scroll class

You can do this either in App.vue or in your main.css (I prefer the latter). In the end, it should look like this:

body.no-scroll {
  overflow: hidden;
}

Finally, you just need to use it

Like any other mixin, you just need to use it in the component you want, like this:

<script>
  import noScrollMixin from '@/mixins/noScrollMixin'
  export default {
    mixins: [noScrollMixin]
  }
</script>
Taha Shashtari

I'm Taha Shashtari, a full-stack web developer. Building for the web is my passion. Teaching people how to do that is what I like the most. I like to explore new techniques and tools to help me and others write better code.

Subscribe to get latest updates about my work
©2024 Taha Shashtari. All rights reserved.