Using the swiper carousel on WordPress results in an unexpected horizontal scrolling issue

Running an Elementor website, I need to incorporate various image carousels within my post content. Initially, I created a template for each carousel using Elementor. However, I have now decided to switch to utilizing a shortcode that leverages Elementor's included swiper feature for creating the carousels. Here is the code snippet:

function custom_carousel_shortcode($atts) {
    
    $atts = shortcode_atts(
        array(
            'ids' => '',
        ),
        $atts,
        'custom-carousel'
    );

    $image_ids = explode(',', $atts['ids']);

    $carousel_html = '';

    foreach ($image_ids as $image_id) {
        $image_url = wp_get_attachment_image_url($image_id, 'full');
        if ($image_url) {
            $carousel_html .= '<div class="swiper-slide"><img src="' . esc_url($image_url) . '" class="swiper-slide-img" /></div>';
        }
    }

    $output = '<div class="elementor-widget-container"><div class="elementor-element elementor-widget elementor-image-carousel"><div id="swiper_init" class="swiper-container"><div class="swiper-wrapper">' . $carousel_html . '</div><div class="swiper-pagination"></div><div class="swiper-button-prev"></div><div class="swiper-button-next"></div></div></div></div>';

    $output .= '<script>
    jQuery(document).ready(function($) {
        $(window).on("load", function() {
            console.log(elementorFrontend.utils);
            let mySwiper;
            const swiperElement = $(".swiper-container");
            const swiperConfig = {
                //centeredSlides: true,
                loop: false,
                pagination: {
                    el: ".swiper-pagination"
                },
                navigation: {
                    nextEl: ".swiper-button-next",
                    prevEl: ".swiper-button-prev"
                },
                //autoplay: {
                //  delay: 5000
                //},
                //slidesPerView: 1,
                //slidesPerGroup: 1,
            };
            //
            if (typeof elementorFrontend.utils.swiper === "function") {
                new elementorFrontend.utils.swiper(swiperElement, swiperConfig).then((newSwiperInstance) => {
                    
                    console.log("New Swiper instance is ready: ", newSwiperInstance);
                    mySwiper = newSwiperInstance;
                });
            } else if (typeof Swiper === "function") {
                console.log("Swiper global variable is ready, create a new instance: ", Swiper);
                mySwiper = new Swiper(".swiper-container", swiperConfig);
            } else {
                console.error("Swiper initialization failed.");
            }
        });
    });
    </script>';

    return $output;
}
add_shortcode('custom-carousel', 'custom_carousel_shortcode');

The swiper functionality loads correctly in my testing environment and retrieves images based on their IDs. However, I am facing an issue with the layout. When only one slide is displayed, additional slides are positioned to the left or right of the screen, causing horizontal scrolling. How can I resolve this and achieve a carousel layout similar to Elementor's native carousel widget? Do I need to tweak the swiper settings or utilize CSS?

UPDATE

I resolved the CSS issue by applying the suggested rule from the comments. Now, I've encountered a new problem where multiple instances of the shortcode on a page result in only the first carousel functioning properly. Upon inspecting the console, I noticed that the swiper instance targets only the initial carousel inserted on the page and not subsequent ones. How can I rectify this secondary issue?

Answer №1

To control the number of slides shown simultaneously, adjust the slidesPerView setting.

In order to prevent a horizontal scrollbar from appearing, apply overflow-x: hidden; to your container element (for example, .slide-wrapper).

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

What could be the reason for the body background color refusing to change

I'm currently working on a JavaScript calculator project and I'm using this code snippet from codepen. The issue I'm facing is that despite setting the body background color to black, it still appears white. Could there be a spacing problem ...

Troubleshooting Next.js server actions with ESLint error detection

I encountered eslint errors while developing a basic server component with server action: // /app/search/page.tsx export default function Search() { async function updateResults(formData: FormData) { "use server"; await new Promise((r ...

Implementing a Reset Button to Clear Checkboxes with PHP or JavaScript

I'm looking for help with setting up a button to reset the checkboxes on my preferences page. UPDATEL: Here's more information: The solutions provided should only affect checkboxes that are currently selected, not those enabled onLoad. This is ...

Saving the content of a div as a PDF

There are several aspects to consider when it comes to this question, but I'm having trouble finding the information I need. Hopefully someone can provide an answer. Essentially, what I want to achieve is: Imagine a div that is 400 X 400 px in size. ...

Pressing a button within an HTML table to retrieve the corresponding value in that row

How can I click a button inside an HTML table, get the value on the same row and pass it to an input field called FullName? Thanks for your help! <td><?php echo $r['signatoryname'] ?></td> <td ...

How to incorporate Django syntax into CSS styling

Imagine a scenario where a Django site is equipped with numerous stylesheets. CSS and JS files are located in the static/ directory within an app's folder or in the global site directory. Various color themes are employed across different pages, neces ...

Tips for preserving component state during page rerenders or changes

I created a counter with context API in React, and I'm looking for a way to persist the state even when the page is changed. Is there a method to store the Counter value during page transitions, similar to session storage? My app utilizes React Router ...

AngularJS - one-time execution of view generation from .NET controller

Currently, I have an MVC .NET application integrated with AngularJS. In my route provider configuration, I am utilizing the controllers of MVC to retrieve the views as shown below: .when('/Units', { templateUrl: 'Unit/Units' ...

Having trouble getting the Underscore.js template to function correctly with JSON data

Hello there! I have some PHP code $arr = array("title"=>"sample Title", "body"=>"151200"); echo json_encode($arr); The data output is: {"title":"test Title","body":"151200"} When I attempt to use this JSON output in Underscore, I encounte ...

The server's delayed response caused the jQuery ajax request to be aborted

Encountering delayed AJAX response from the PHP server upon aborting the AJAX request. Currently utilizing the CodeIgniter framework for the server script. Javascript Code: cblcurrentRequest = $.ajax({ url: baseurl + 'Login/getChannelBra ...

Utilize JavaScript to Trigger AJAX HoverMenuExtender in .NET

Within my C# web application, I am attempting to trigger an Ajax HoverMenuExtender using JavaScript, rather than relying on hovering over a designated control. When I set the TargetControlID of the HoverMenuExtender to a control on the page and hover ove ...

I am looking to eliminate an object from an array based on the object's unique identifier

I am facing an issue with filtering an object based on the id in order to remove it from the array. The filter function I am using is not working as expected. My goal is to only remove the object that matches the provided id, while sending the remaining ...

Embrace the presence of null values on the client side

When utilizing the code below, I can determine the location of logged-in users. However, there are some users who do not have a specific location assigned. For example, Administrators are common for all locations. In such cases, how can I set it so that ...

Is there a way to determine if an element has been scrolled past?

I am currently working on a script to detect when a specific element comes into view while scrolling. const targetElement = document.getElementById('sidebar'); window.addEventListener('scroll', () => { if (window.scrollY > tar ...

How can I adjust the appearance of an HTML tag within an Angular component?

I have created an Angular component with the following definition: import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'rdc-dynamic-icon-button', templateUrl: './dynamic-icon-button. ...

Maintain MUI Autocomplete in the open state even after making a selection from the

Whenever I select certain options on my Autocomplete component, I want to keep the component open. However, each time I click on onChange, the Autocomplete closes automatically and I can't seem to find a way to prevent this. Is there a workaround? In ...

Trigger an alert message upon clicking a button within CK Editor

Is it possible to trigger an alert message using ckeditor when a specific button is clicked? Below is the code snippet for reference: $(document).ready(function () { $(".cke_button__bold").click(function () { editor.on("CKEDITOR.cke_butto ...

Exploring Vue's reactivity using the composition API and cloning props

In my current component setup, I am receiving props from a parent. However, I am facing an issue where I only want to clone these props without any changes affecting the parent component. <template> <input-text v-model="form.name" /&g ...

How to dynamically adjust font size using Javascript

Is there a way to adjust the font size of the left-column using JavaScript? <div id="left-column"> <a href="">1</a><br> <a href="">2</a><br> <a href="">3</a><br> <a href=""> ...

What is the best approach: Referencing schema within properties or including it as an array in Mongoose?

Consider the scenario where we have two schemas, User and Post. Should we include a reference to User in Post's properties or should we add an array of Post schema inside User schema? Which approach is more efficient in terms of performance and other ...