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

Using an expression from the parent controller to disable an item in an AngularJS directive

I created a list of custom directive items, each with a remove button. The issue I'm facing is that I want to disable the remove button when there's only one item left in the list, but it's not working as expected. To see this problem in ac ...

Fade-in loader with centered placement on the full page

As a newcomer to programming, I wanted to implement a loader that displays a centered loading animation when the page loads or refreshes. The animation should gray out and fade the entire page until it fully loads. I've managed to get everything else ...

Beginner's guide to using Express: a step-by-step tutorial on making API requests from client-side JavaScript to

Currently, I am immersed in a Javascript project where I utilize the Nasa Mars Rover API and Immutable Js to creatively display images and information on my webpage. By harnessing the power of pure functions and functional programming, I maintain app state ...

The enigmatic dance of Angular and its hidden passcodes

Recently, I've been diving into learning Angular 2 and I'm exploring ways to safeguard the data in my application. I'm curious about how one can prevent data from being accessed on the front end of the app. Could serving the angular app thr ...

Unable to trigger jQuery onclick event on nested div elements

I'm experiencing an issue with my web-page where two buttons at the top are not responding to a sorting function on the nested #byFilter. Despite trying to apply the onclick(function()) method, it doesn't seem to work. Javascript $(document).re ...

Invoking numerous functions through the (click)= event

When it comes to removing a user from my site, I find myself having to execute multiple database queries to delete the user's ID across approximately 10 different tables. Currently, I am resorting to what I consider a messy workaround where I have mu ...

Using JQuery, retrieve all field values on click, excluding the value of the closest field in each row

I have a dynamic table where each row consists of an input field and a button. I am searching for a simpler way to select all input fields except the one in the current row when clicking the button in each row. All input fields have the same name and the r ...

Retrieving data from a textbox using JavaScript within an Excel VBA setting

I'm encountering an issue with a Macro in Excel where I need to retrieve the value of an "input type="text"" on a JavaScript webpage. However, the value is not specified in the code (value=""), and it remains unchanged even when the webpage displays t ...

Vuejs tutorial: Toggle a collapsible menu based on the active tab status

I am using two methods called forceOpenSettings() and forceCloseSettings() to control the opening and closing of a collapsible section. These methods function properly when tested individually. However, I need them to be triggered based on a specific condi ...

The color attribute enhances the appearance with a colored border specifically designed for Chrome users

Starting off, I appreciate the border that Chrome applies to my inputs. However, I am facing an issue with the textarea element. The problem is that the textarea uses the color attribute not only for coloring the text but also as the border color. Here is ...

Slide containing Ionic list views

In my Ionic app, I am using ion-slide-box with 3 slides. Each slide contains an ion-list (table view) with varying numbers of items. The issue is that when scrolling through the shorter list items, it shows empty content due to the taller sibling list taki ...

What factors should I consider when choosing the appropriate socket for receiving messages from a RabbitMQ queue?

I have encountered an issue while trying to connect to a queue on a remote server using Rabbit.js. Every attempt to connect results in the following error message: Error: Channel closed by server: 406 (PRECONDITION-FAILED) with message "PRECONDITI ...

Having trouble getting Angular Filter to work within a directive expression?

I am currently working on a directive where I need to convert both the attribute and object name values to lowercase. I have tried using filters, as well as the $filter service, but it doesn't seem to be working. Can anyone please provide assistance i ...

Dynamic web elements can be easily enhanced through the use of jQuery

Upon loading a page through AJAX, I encountered the following code involving animation of a div (#1 moves it to the left and #2 moves it back): #1 $('#flipper').click(function () { $(".l-l").animate({ "left": -267 }, 600, function () { ...

LeafletJS and ReactJS integration causing misalignment in tile ordering

In my ReactJS single page application, I am utilizing the LeafletJS plugin to showcase a full-page map. Even after following the guidelines mentioned here, I am facing an issue where the map tiles are not displayed in the correct order and appear to be shu ...

JavaScript: Creating Custom IDs for Element Generation

I've been developing a jeopardy-style web application and I have a feature where users can create multiple teams with custom names. HTML <!--Score Boards--> <div id="teamBoards"> <div id="teams"> ...

When attempting to open the HTML file through an Express application, the background image specified by `background-image: url()` may

Upon opening the html file by directly clicking on it, the background-image styled with url() functions correctly. However, when I open this file within an express app using res.sendFile(), the background-image fails to display. Interestingly, all other CS ...

fewer security personnel leads to a higher success rate

I've tried searching for it online, but unfortunately, I couldn't find any helpful results. What I'm attempting to achieve is a mixin that can lighten or darken a color based on a given percentage. If the percentage is less than 0, then I w ...

Internet Explorer not triggering jQuery blur() or focusout() events

Having some issues with my form and event handling when the inputs lose focus. The code is working perfectly in every browser except for Internet Explorer. function formstyle() { var focus = 0; //comentario is the ID of the input $("#comenta ...

Is there a way to prevent a premature closure of a connection?

I'm currently faced with the task of moving a substantial amount of data from a MySQL database, exceeding the maximum query size. To accomplish this, I need to process it in chunks through a loop. However, encountering an issue where about half of the ...