Adjusting a Swiper JS parameter on the fly

Currently, I am attempting to dynamically adjust the eventsTarget within the mousewheel object in Swiper based on changes to a data property using Vue.js. Specifically, when disableBodyScroll is set to true, the carousel should scroll via eventsTarget:html; otherwise, it should utilize the default swiper container:

  data() {
    return {
      disableBodyScroll: false,
    }
  },

  async mounted() {
    await this.$nextTick()
    this.initSwiper()
  },

 methods: {
    initSwiper() {
      const vm = this

      if (this.$refs?.carousel) {
        this.carousel = new SwiperCore(this.$refs.carousel, {
          mousewheel: {
            eventsTarget: this.disableBodyScroll ? 'html' : 'container',
            releaseOnEdges: true,
            thresholdDelta: 1,
          },
          freeMode: this.mousewheelScroll,
          freeModeSticky: this.mousewheelScroll,
          on: {
            reachEnd: (swiper) => {
              vm.disableBodyScroll = false
              swiper.params.mousewheel.eventsTarget = 'container'
              swiper.update()
            },
            reachBeginning: (swiper) => {
              vm.disableBodyScroll = false
              swiper.params.mousewheel.eventsTarget = 'container'
              swiper.update()
            },
          },
        })
      }
    },
  },

I have tried various approaches to change the value of the disableBodyScroll data property, but unfortunately, none of them have been successful. Despite my efforts, the behavior remains unchanged. One workaround I have implemented involves utilizing a watcher that destroys and reinitializes the carousel upon detecting a change in the disableBodyScroll property.

watch: {
  disableBodyScroll(newVal) {
    if (this.carousel) {
      this.carousel.destroy(true, false);
      this.initSwiper();
    }
  },

However, this method resets the Swiper carousel to its initial state and does not provide an ideal user experience. Additionally, explicitly setting the eventsTarget and invoking update() when reaching the end or beginning of the slides has also proven ineffective.

Do you have any insights on a potential solution for achieving this dynamic behavior?

Answer №1

Updating Swiper JS parameters can be achieved using .setAttribute(), as mentioned in the official documentation. However, this method may not work for modules like the Mousewheel module.

Fortunately, you can still achieve the same effect without having to update any attributes.

Answer

To control the mousewheel events, create a wrapper element and assign it to mousewheel.eventsTarget. Set the size of the element to match the html body (e.g. 100vh) or the container based on the .bodyScroll data property.

<template>
  <div class="wheel-control" :style="wheelControlStyle">
    <div class="swiper" ref="carousel">
      <div class="swiper-wrapper">
        <!-- Slides -->
        <div class="swiper-slide">Slide 1</div>
        <div class="swiper-slide">Slide 2</div>
        <div class="swiper-slide">Slide 3</div>
      </div>
    </div>
    <button @click="updateEventsTarget">change mousewheel eventstarget</button>
  </div>
</template>
export default defineComponent({
  data() {
    return {
      bodyScroll: true
    }
  },
  computed: {
    wheelControlStyle() {
      // adjust height based on body-scrolling requirement
      return { height: this.bodyScroll ? '100vh' : 'auto' }
    }
  },
  async mounted() {
    await this.$nextTick()
    this.initSwiper()
  },
  methods: {
    initSwiper() {
      console.log('refs', this.$refs)
      if (this.$refs?.carousel) {
        this.$carousel = new Swiper(this.$refs.carousel as HTMLElement, {
          mousewheel: {
            eventsTarget: '.wheel-control',
            releaseOnEdges: true
          }
        })
      }
    },
    updateEventsTarget() {
      console.log('updating')
      if (!this.$carousel) return
      this.bodyScroll = !this.bodyScroll
    }
  }

Check out the working demo on Github: here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stack screen not visible on React Native navigation

I'm currently utilizing the React Native Navigation library for routing. However, I've encountered an issue with the code below that doesn't seem to be functioning as expected. My objective is to set up two screens - one for login and the o ...

A step-by-step guide on creating a live crud application with vuex and socketio

I am struggling to achieve a realtime crud operation using vuex, node, express, and socketio with the current syntax provided. Here is the code snippet: Server index.js const server = app.listen('3000',() => { console.log('<--- ...

Using an if statement to run a script in Npm

Is there a way to configure an npm run script to use different AWS accounts based on the environment? { "config": { "acc": if ({npm_config_env} == "dev") "account1" else "account_2" }, "scr ...

Retrieve vue environment variables within a template

I am trying to figure out how to access my environment variables directly from the template of Vue single file components. When attempting to do so like this: <img :src="`${process.env.VUE_APP_API_BASE_URL}/image/${image.filename}`" alt=" ...

Offer utility methods access to a Redux store

I have a question regarding JavaScript design and how to integrate a redux store with non-React components. In my typical react-redux application, I currently handle all service calls in a centralized functional utility file called fetches.js instead of di ...

Utilize the toString function along with the substring method within an ejs template

I am attempting to showcase an employee's ID by displaying only the last four digits in a table on an EJS page. The data is stored in MongoDB and I am using Express for handling routes. Here is my Express route: app.get('/routehere', async ...

Encountering an Issue with Vue 3 and Vue Router 4: Uncaught TypeError - Trying to Access Undefined Properties (specifically 'push')

I'm currently working with Vue 3, Vue Router 4, and TypeScript in my project. However, I've encountered an issue while trying to utilize router.push(). Every time I attempt this, I receive a console error stating: Uncaught (in promise) TypeError: ...

Sorting may produce varied results across various web browsers

function sortResults(type) { $("#parentDiv").empty(); $.getJSON("raw_data.json", ({ Search }) => { Search.sort((a, b) => a[type] > b[type]); console.log(`Sorted by: ${type}`); ...additional code Browser compatib ...

Having Trouble with jQuery Datepicker in IE8 - Need Unique Solutions

After visiting numerous websites, I am still unable to solve this issue. The error I am encountering (only in IE8, works fine in Chrome, FF, IE9 and IE10) occurs when using IE10 in the IE8 browser mode. Despite testing with IE8, the business department is ...

utilize dynamic variables in post-css with javascript

Question: Is it possible to dynamically set or change variables from JavaScript in post-css? I have a react component with CSS3 animations, and I want to set dynamic delays for each animation individually within each component. I've found a similar s ...

extracting an attribute from a class's search functionality

Let's consider the following HTML structure: <div id="container"> <div> <div class="main" data-id="thisID"> </div> </div> </div> If I want to retrieve the value inside the data-id attribute ...

Choose a radio button from a React Native FlatList

I am new to React Native and I'm working with the expo-radio-button component. However, I'm facing an issue where I can't seem to select only one radio button at a time in a flatlist. When I try to select a single button, it ends up select ...

Tips for passing props to multiple child components in Vue?

In Vue, I'm curious about how to achieve the same functionality as declaring an object in React and passing it to multiple child components. const shared_props = { prop1: 'value1', prop2: 'value2', prop3: 'value3', ...

Move divs on top of each other while scrolling through a webpage

I am working on an HTML-page that contains multiple DIVs and a function called 'fullscreenCSS' that ensures the DIVs take up the entire screen. My goal is to create a scrolling effect where as I scroll using the scrollbar, the current DIV remain ...

Encountered an abrupt termination of JSON input while implementing Promise.all() alongside the fetch method's put operation

Encountered an issue with JavaScript while attempting to retrieve mail content from an API and update its read status simultaneously. The error message displayed in the console is: SyntaxError: Unexpected end of JSON input at inbox.js:98 The error pro ...

What is the process for executing JavaScript code that is stored as a string?

After making an AJAX call, I receive a random string (constructed dynamically on the server) that contains JavaScript code like: Plugins.add('test', function() { return { html: '<div>test</div&g ...

Utilizing an object's attribute to reference an image for a source

I am encountering an issue trying to display an image from the video object's image attribute on the screen when my program runs. The problem lies in the fact that there is no file named 'videoObj1.image', which causes a source error. I am e ...

Modify the styling of the Checkbox within the script template

I am currently working with a list that contains checkboxes, but they are displaying with the default CSS style. How can I change the CSS style of the checkboxes? Below is the code I am using, and I need to modify the CSS of the checkboxes. <div id ...

I am looking to organize my content by creating categories such as How, When, and Why for different videos. How can I achieve this for a large amount of text

I am in the process of organizing categories for the text I have. My goal is to display text from specific categories based on the color that a random video lands on. For example, if the video lands on the color red, I want text from the category labeled " ...

Retrieve the runtime configuration object or file using Jest

Is there a way to access the Jest runtime config object or file path? I wanted to utilize runtime config properties in my custom matchers. // ./jest.config.js const path = require("path"); module.exports = { prop1: "foo", prop2: "bar" }; // my-custo ...