Ways to eliminate numerous swipe features in JavaScript on a webpage

Struggling to handle multiple swipers on the page, encountering an issue where the array is always empty in the destroy function for desktop width. The initialization process for mobile devices seems to be working fine. Have tried various methods but end up with an empty array every time.

   var init = false;
    function swiperManager() {
        let mobile = 972;
        let allWorks = document.querySelectorAll('.work-item__images');
        let swiperArray = [];

        const createSlider = (element, id) => {
            return new Swiper(element, {
                loop: true,
                observer: true,
                observeParents: true,
                slidesPerView: 2.5,
                spaceBetween: 16,
            });
        }

        // Enable slider for mobile view

        
        console.log(document.body.getBoundingClientRect().width);
        if(document.body.clientWidth <= mobile) {
            if (!init) {
                init = true;
                allWorks.forEach((item, id) => {
                    const slider = createSlider(item, id);
                    swiperArray[id] = slider;
                    console.log(swiperArray);
                })
            }
        }
        console.log(swiperArray);
        if (document.body.clientWidth > mobile) {
            console.log(swiperArray, 2);
            if ( swiperArray.length === 0) return;
            for (let i = 0; i < swiperArray.length; i++) {
                console.log(swiperArray[i]);
                swiperArray[i].destroy(true, true);
            }
            swiperArray = [];            
            init = false;
        } 
        
    }

    /* On page load
    **************************************************************/
    window.addEventListener('load', function() {
        swiperManager();
    });

    /* On resize
    **************************************************************/
    window.addEventListener('resize', function() {
        swiperManager();
    });

Answer №1

The answer was quite straightforward

let initialized = false;
function toggleSwiper() {
    let mobileWidth = 972;
    let allImages = document.querySelectorAll('.work-item__images');

    const createSlider = (element, id) => {
        return new Swiper(element, {
            loop: true,
            observer: true,
            observeParents: true,
            slidesPerView: 2.5,
            spaceBetween: 16,
        });
    }


    if(document.body.clientWidth <= mobileWidth) {
        if (!initialized) {
            initialized = true;
            allImages.forEach((item, id) => {
                const slider = createSlider(item, id);
            })
        }
    }
    if (document.body.clientWidth > mobileWidth) {
        allImages.forEach(function(item) {
            if (item.swiper) item.swiper.destroy(true,true);
        })      
        initialized = false;
    }         
}

/* On Load
**************************************************************/
window.addEventListener('load', function() {
    toggleSwiper();
});

/* On Resize
**************************************************************/
window.addEventListener('resize', function() {
    toggleSwiper();
});

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

Removing all newlines in an array in C# without utilizing a for loop

To eliminate all line breaks from the input without utilizing a for loop and potentially altering the array order, the code needs to be inserted at the marked line below. string[] filterInput1 = tbInput1.Text.Split(new string[] { Environment.NewLine }, St ...

Can anyone explain how to pass a toggle state along with its onChange function in Ionic React?

Imagine I have this toggle element: <IonToggle id="IonToggleDarkMode" slot="end" checked={vars.darkMode} onChange={darkModeToggle}></IonToggle> The value of vars.darkMode represents the current state of the toggle, which is ...

Changing the state with alternative values is ineffective

To help illustrate my issue, I have created a simple sandbox environment: https://codesandbox.io/s/wizardly-fermat-egww0?file=/src/App.js Problem description: In my e-commerce application, there are 2 products, each with 2 different color variants. At t ...

Universal Module Identifier

I'm trying to figure out how to add a namespace declaration to my JavaScript bundle. My typescript class is located in myclass.ts export class MyClass{ ... } I am using this class in other files as well export {MyClass} from "myclass" ... let a: M ...

Guide to linking audio to MediaStream using Three.JS AudioContext

I have a MediaStream created from a canvas and I am trying to add audio to it from the Three.js audio stream. After attempting various methods, I found that the most concise solution is shown in the code snippet below. The stream seems to be added success ...

Creating a structure for data in Ruby on Rails to facilitate AJAX calls to controller actions

I am in need of a button on my website that can send data to the create action of a controller named "pagetimes". The functionality seems to be partially working, but it is not sending all the specified data. This issue may be due to my inability to struct ...

Having trouble with connecting to Gmail while using Nodemailer? Facing a Connection Timeout

Seeking assistance with sending emails through nodemailer. See below for the code snippet. var transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: '<<a href="/cdn-cgi/l/email-protecti ...

Prevent caching of JavaScript variables in EJS mode

Is there a way to turn off ejs cache? I came across a solution: ejs.clearCache() However, this method requires an instance of ejs to work. Currently, I am only using: app.set('view engine', 'ejs'); Therefore, I am unsure how to cle ...

Make real-time edits to JavaScript code on a webpage

Is there a method aside from using Firebug in the DOM view to edit live JavaScript embedded within an HTML page? For example, code like this within a .html file: <script type="text/javascript> // code here </script> Thank you. ...

Sides of the BoxGeometry

I previously inquired about a particular issue on this post: Adding Thickness to Faces The main problem has been resolved, but now I have encountered a new issue. Initially, my walls were set to side:THREE.BackSide so they didn't display when facing ...

Activate each division separately with a single script

I am facing an issue where each blue div (<div id="rectangle"></div>) is not firing independently when hovered or clicked. Currently, when I hover/click over the first one, both fire simultaneously. However, if I hover/click over the second on ...

Unusual display of feedback text in Bootstrap 4

When I directly copied this code snippet from Bootstrap 4: <div class="form-group has-danger"> <label class="form-control-label" for="inputDanger1">Input with danger</label> <input type="text" class="form-control form-contro ...

You've got a function floating around without any specific theme tied to it. Make sure one of the parent elements is utilizing a ThemeProvider for proper context

I am working on implementing a Navbar in my current Project. The dependencies I am using are: mui/icons-material: ^5.2.5 mui/material: ^5.2.6 mui/styles: ^5.2.3 Here is the folder structure of my project: Root.jsx Navbar.jsx styles ...

Can anyone suggest a more efficient approach to handling variations using CSS?

Within the message component, there are currently only two variants available: error and success. This project is built using vue3 script setup and utilizes SCSS for styling. <script setup lang="ts"> defineOptions({ name: 'Notificat ...

What is the best way to update an existing cookie value using angularjs?

Currently, I am working with AngularJS. When a button is clicked, I am setting a cookie and it works perfectly fine. However, when the page is refreshed and another button click occurs, a new value is stored in the array while the old cookie value becomes ...

GTM - monitoring the most recent clicked element's input data

Custom Script function() { var inputs = document.getElementsByTagName("input"), selectedRadios = []; for (var i = 0;i < inputs.length;i++) { if(inputs[i].type==="checkbox" && inputs[i].checked) { selectedRadios.push(inputs[i].value); ...

Angular - How child components can communicate with their parent components

I'm struggling to understand how to communicate between components and services. :( Even though I've read and tried a lot, some examples work but I still don't grasp why (?). My goal is to have one parent and two child components: dashboa ...

Exploring the concept of segmentation fault when using a fixed-size array of std::tuple within a class

For my image processing project, I needed to store three data points for each pixel in an image. To achieve this, I decided to use std::tuple within my CameraManager class: class CameraManager { private: static const int width_ = 700; static cons ...

What steps can I take to improve the efficiency of this filtering process in Vue.js?

I am seeking ways to enhance the method I utilize for determining which values should be displayed in a table. At present, my table displays various values and is accompanied by input fields. The values chosen in these input fields serve as filters for the ...

Create a custom npm package that is compatible with frontend environments like create-react-app. Ensure you have a suitable loader in place to handle the specific file type of the module

After developing a node module and releasing it as a node package, I encountered an issue when trying to use it in frontend applications (specifically with a 'create-react-app'). The error message that appeared stated: Module parse failed: Unexp ...