Connecting to a specific slide within a carousel using an array of thumbnails

Utilizing a gallery field from ACF in WordPress, I aim to showcase all images as thumbnails with a Masonry layout. When an image is clicked, it should open a carousel within a modal and navigate directly to the corresponding slide.

The code below effectively displays the image thumbs:

<?php $galleryImages = get_field('image_gallery'); 
if ($galleryImages): ?>

<div id="image-gallery" style="margin: auto" class="grid" data-masonry='{ "itemSelector": ".grid-item", "columnWidth": ".grid-sizer", "gutter": 10, "fitWidth": "true" }'>
    <div class="grid-sizer"></div>
    <?php $slideNumber = 0; ?>
    <?php foreach ( $galleryImages as $image ): ?>

    <div class="grid-item">
        <a href="#carousel-modal" data-toggle="modal" data-slide-to="<?php echo $slideNumber; ?>">
            <img class="gallery" src="<?php echo $image['sizes']['medium']; ?>">
        </a>
    </div>

    <?php 
    $slideNumber++;
    endforeach; ?>

</div>

The modal carousel is successfully generated using this code:

<div class="modal fade" id="carousel-modal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="carousel" class="carousel slide" data-ride="carousel">
                    <div class="carousel-inner">
                        <?php $class = 'carousel-item active'; ?>
                        <?php foreach ( $galleryImages as $carouselSlide ): ?>
                        <div class="<?php echo $class; ?>">
                            <img class="d-block w-100" src="<?php echo $carouselSlide['sizes']['large']; ?>">
                        </div>
                        <?php $class = 'carousel-item'; 
                endforeach; ?>
                    </div>

                    <a class="carousel-control-prev" href="#carousel" role="button" data-slide="prev">
                        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                        <span class="sr-only">Previous</span>
                    </a>
                    <a class="carousel-control-next" href="#carousel" role="button" data-slide="next">
                        <span class="carousel-control-next-icon" aria-hidden="true"></span>
                        <span class="sr-only">Next</span>
                    </a>

                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<?php endif; ?>

When clicking on an image, the carousel opens but doesn't start at the selected image, instead proceeding through its sequence. How can I ensure it opens at the right image?

I attempted adding data-target="#carousel" to the a surrounding the img, yet this didn't work as expected - it just darkened the screen upon click.

UPDATE: The same code functioned perfectly on another website. It seems like a Javascript issue, though my expertise in that area is limited. Any guidance on where to begin troubleshooting would be appreciated.

Answer №1

Unexpectedly, an idea struck me:

Make a change by replacing the data-slide-to attribute on the a with

onclick="$('.carousel').carousel(<?php echo $slideNumber; ?>)"
. Surprisingly, it worked flawlessly.

The previous website was just a stroke of luck. It turned out that one of the plugins it utilized unknowingly added some script that made everything function smoothly.

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

Angular CLI may not always detect newly added tests without manual intervention

When initiating an Angular-cli test using ng test only the already defined tests are executed. Any addition or deletion of a test is not automatically detected (i.e. the test count remains the same). Restarting the command refreshes the current test suit ...

The final item in the inline list vanishes when a new list is added

I wrote a PHP script that creates an array of images from a specific folder: <?php $imagesDir = 'thumbnails/'; $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE); echo json_encode($images); ?> Th ...

ERROR: Expo TaskManager Notifications [TypeError: Attempting to call an undefined function (near '...Notifications.presentLocalNotificationAsync...')]

I'm currently trying to figure out how to send notifications whenever a task is triggered, but I keep encountering an error that I can't seem to fix. Here's the error message: TaskManager: Task "background-fetch" failed:, [TypeError: unde ...

Having trouble retrieving information from the database using socket.io and node.js

As a beginner in node.js and socket.io, I am experimenting with my simple project to fetch data from a database. My index.html serves as a real-time chat example using socket.io with a basic ajax request. <!doctype html> <html> <head> ...

Unable to make a successful POST request using the JQuery $.ajax() function

I am currently working with the following HTML code: <select id="options" title="prd_name1" name="options" onblur="getpricefromselect(this);" onchange="getpricefromselect(this);"></select> along with an: <input type="text" id="prd_price" ...

Interpreting HTML with JavaScript

Currently, I am attempting to parse an HTML document. This is the given HTML snippet: <div> <a class="profilePicThumb" href="https://www.facebook.com/photo.php?fbid=669986173135523&amp;set=a.219741158160029.56045.100003724408511&amp; ...

Angular click directive

Exploring AngularJS and attempting to modify an example from a tutorial. I want the ng-init value to be equal to the value passed from a script function. How can I achieve this? Here's the code snippet: <html> <body> <h2> ...

all elements with equal height within a flexbox positioned at the bottom

Check out this HTML code snippet I have for constructing a grid using Bootstrap 4: <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOh ...

A guide on updating progress bar value based on user input

I have an input field and a progress bar that needs to be updated based on the input. The task is to input a number (%) and then display that value in the progress bar upon clicking the "Apply" button (btn-primary). Below is the HTML code provided: < ...

Having trouble installing npm package in Angular project

After cloning my project from GitLab, I encountered an issue while trying to install the NPM packages. When I ran npm install, an error popped up: https://i.stack.imgur.com/WNT5s.png Upon checking the log file, I found the following error message: 3060 ...

What is causing the React text component to fail to show changes made to my array state?

I am currently in the process of learning React Native. I have been working on an app and encountered an issue while attempting to update individual elements within an array. Here is an example of the code: function MyApp() { const [array, setArray] = ...

Issues with the functionality of the jQuery notify plugin are being encountered when used in a

I am currently utilizing the jQuery notify plugin and have included all the necessary JS files in the header. However, whenever I attempt to call the $.notify function in another JS file that also involves AJAX, I encounter difficulty accessing the $.notif ...

Are simulated AJAX requests a viable solution for displaying a "wait" cursor?

While I initially wanted to use the CSS cursor property to put the user's cursor in a "wait-state" during certain actions, I encountered issues that are pushing me to explore more innovative solutions. The main problem is that the cursor doesn't ...

React not triggering onChange event for Bootstrap toggle button group

Utilizing the toggle button group from bootstrap to choose a platform option is my goal. However, I am facing an issue where the onChange event is not triggering. class Hello extends React.Component { constructor(props) { super(props); this.hand ...

Issue with Material UI tabs: TypeError - Unable to access property 'charAt' as it is undefined

Currently, I am attempting to implement Material UI tabs in my project. Here is the component in question: const ItemssOverview = ({ details }) => { if (details && details.items) { return ( <div> &l ...

No pathways can be established within Core UI Angular

I've been attempting to use the router link attribute to redirect to a new page, but instead of landing on the expected page, I keep getting redirected to the dashboard. Below is an overview of how my project's structure looks: [![enter image de ...

Print page headers are being overlapped by THEAD elements

I have created a table and am considering using the thead as page headers if the table spans multiple pages. However, I am encountering an issue where the content of the table overlaps with the table header on the second page. Here is a snippet of my HTML ...

The error message "TypeError: Unable to access property of undefined when using web sockets"

Exploring Isomorphic framework for React and integrating Pusher for websockets communication. I'm encountering difficulty accessing the state within the componentDidMount() function. class TopbarNotification extends Component { state = { vis ...

Issues with Angularjs $http.get functionality

On the server side of my ASP.net MVC application, I have a method that looks like this: [HttpGet] public JsonResult GetTrenings(string treningId) { var tempId = Guid.Parse(treningId); var trening = TreningService.GetTreningById ...

Automatic playback of the next video in a video slider

Looking to upgrade my video slider functionality - switching between videos, playing automatically when one finishes. Struggling to find a solution that combines manual control with automatic playback. My attempt: function videoUrl(hmmmmmm){ ...