The previous button on Owl Carousel seems to be malfunctioning after navigating from a different page

In my case, I have two distinct pages: let's call them the first and second pages.

On the first page, I utilize an owl carousel slider with a tag that links to a specific slide on the second page's owl carousel slider using an ID. Meanwhile, on the second page, there are previous and next buttons that change names each time the user switches slides to guide them. Everything seems to work fine until the user navigates from the first page to the second one and attempts to click the previous button right away, which doesn't function correctly. However, if they click the next button first and then the previous one, it works as intended. Here are the relevant code snippets:

FIRST PAGE

<div class="owl-carousel home-page-project-design home-page-manufacturing-list">
        <a href="../project-design-showcase.php#walk-in-wardrobes">
            ...
            content goes here
            ...
        </a>
        ... more similar layout for other sections ...
    </div>
    

SECOND PAGE

<section class="next-and-previous-title-showcase">
        ...
        additional details displayed in this section can be found here
        ...
    </section>

    <div class="owl-carousel test3">
        ...
        include corresponding files for different carousel slides
        ...
    </div>

    <script>
        ...
        jQuery script inside this section controlling the functionality of the carousel
        ...
    </script>
    

Answer №1

SOLUTION

<script>
$(document).ready(function() {
    var fragmentMap = {
        'custom-closets': 0,
        'living-rooms': 1,
        'dining-areas': 2,
        'home-offices': 3,
        'entertainment-centers': 4,
        'wine-cellars': 5,
        'patios': 6
    };

    var owl = $('.test3').owlCarousel({
        stagePadding: 10,
        responsive: {
            0: {
                items: 1
            },
            768: {
                items: 1
            },
            1280: {
                items: 1
            }
        },
        touchDrag: true,
        mouseDrag: false
    });

    function updateButtonLabels(currentItem) {
        $('.prev-button').text(prevButtonLabels[currentItem]);
        $('.next-button').text(nextButtonLabels[currentItem]);
    }

    var nextButtonLabels = [
        'Living Rooms',
        'Dining Areas',
        'Home Offices',
        'Entertainment Centers',
        'Wine Cellars',
        'Patios',
        ''
    ];

    var prevButtonLabels = [
        '',
        'Custom Closets',
        'Living Rooms',
        'Dining Areas',
        'Home Offices',
        'Entertainment Centers',
        'Wine Cellars'
    ];

    var currentItem = 0;

    // Get the fragment identifier from the URL
    var fragment = window.location.hash.substring(1);

    if (fragmentMap.hasOwnProperty(fragment)) {
        currentItem = fragmentMap[fragment];
    }

    // Initialize the Owl Carousel with the currentItem
    owl.trigger('to.owl.carousel', [currentItem, 0, true]);
    updateButtonLabels(currentItem);

    $('.prev-button').click(function() {
        if (currentItem > 0) {
            owl.trigger('prev.owl.carousel');
            currentItem--;
            updateButtonLabels(currentItem);
        }
    });

    $('.next-button').click(function() {
        if (currentItem < prevButtonLabels.length - 1) {
            owl.trigger('next.owl.carousel');
            currentItem++;
            updateButtonLabels(currentItem);
        }
    });
});
</script>

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

Search through array elements that are nested deeply

Consider the following scenario: an array is provided as input containing various objects with nested elements. The goal is to filter this array in JavaScript and obtain a new array consisting only of objects where the key "navigation" has a value of true. ...

Creating a Discord Bot: Building an Embed Table/List with Segmented Sections

Currently in the process of learning Javascript and venturing into discord.js, I'm fully aware that the code I am working with is not up to par and requires some serious refinements. The main objective here is to split up the arguments of a command a ...

Event follows activation of trigger click

I've already gone through this post on Stack Overflow about triggering an action after a click event, but none of the solutions I've tried so far have worked. Let's say I have a menu on my webpage like this: <ul class="nav nav-tabs"&g ...

What is the process for retrieving a JavaScript script generated by PHP through AJAX and executing the script successfully?

Utilizing the Google Maps API, I am in the process of creating my very own world. However, I have encountered a problem where the large number of markers/locations is causing the page to become unresponsive. I suspect that the solution lies in calling onl ...

Security Error when using the JavaScript map function in FireFox

My current dilemma involves using a JavaScript code to extract the above-the-fold CSS from my websites. Surprisingly, it functions flawlessly on Google Chrome. However, when I attempt to execute it on Firefox, an infamous 'SecurityError' occurs: ...

Utilizing Material UI tabs panel with customized CSS styling

Having trouble changing colors and CSS in the TAB PANEL using material-ui. Any tips or suggestions? :( It seems like useStyle and theme functions are not working as expected. I was able to modify other properties like scrollable, but colors seem to be fix ...

How to update data in AngularJS grid component using ng-bind directive

As a newcomer to AngularJS, I'm facing an issue that I need help with. Here's my problem: I have an ng-grid connected to a table. Inside the grid, there are values along with an ID (which is a foreign key from another table). Instead of display ...

To ensure proper display, the canvas should be set to display block when its width is 100vw and height is 100vh

Can anyone explain why I need to include display: block when my canvas is full page? Without it, the canvas size appears larger even though the width and height values are the same. Appreciate any insights. Thanks! ...

Issues with Django Posts Functionality:

Currently, I am utilizing Django 1.2.3 for the development of a website. While my ajax get requests are functioning properly, the post requests only work in development mode (127.0.0.1:8000) and not when the site is deployed in production using Apache + Ng ...

Retrieving JavaScript array data following a page reload

I am facing an issue with updating an array dynamically in my C# server-side code and then utilizing the updated data in a JQuery function on my webpage. When the page first loads, the array is filled with some default values by C#. However, when a user ma ...

How can you ensure that the right data types are sent through ajax requests?

My goal is to ensure the server receives data in the correct data type when using ajax. For example, I want boolean values to be received as actual booleans, integers as integers (not strings), and so on. I attempted a solution where I sent the data as JS ...

Display images in a list with a gradual fade effect as they load in Vue.js

In my Vue project, I am looking to display images one at a time with a fading effect. I have added a transition group with a fade in effect and a function that adds each image with a small delay. However, I am facing an issue where all the images show up ...

Looping through an array of JSON objects in Javascript results in finding instances, however, the process records them

Currently, I am executing a script inside a Pug template. The script commences by fetching an array of JSON objects from MongoDB. I then stringify the array (data) and proceed to loop through it in order to access each individual JSON object (doc). Subsequ ...

How can I efficiently generate a table using Vue js and Element UI?

I am utilizing element io for components. However, I am facing an issue with printing using window.print(). It currently prints the entire page, but I only want to print the table section. ...

Difficulty with conflicting styles when dynamically loading components in Nuxt3

I'm facing a challenge with my Nuxt 3 application where I need to dynamically load different Header components for Mobile and Desktop devices. I have created Header.vue and MobileHeader.vue for this purpose, and want to display them based on the dev ...

Expanding Material Ui menu to occupy the entire width of the page

I'm encountering an issue with a menu I created where I can't seem to adjust its height and width properly. It seems to be taking up the full width of the page. import React, { Component } from "react"; import Menu from "@material-ui/core/Menu"; ...

Encountering an issue with extending the MUI color palette, receiving a "reading 'dark'" error due to properties of undefined

Encountering an issue when trying to expand the MUI color palette—getting this error instead: Error: Cannot read properties of undefined (reading 'dark') Take a look at my theme.ts file below: const theme = createTheme({ palette: { pri ...

Managing global errors and intercepting requests in AngularJS can be easily achieved by utilizing $resource interceptors and global handlers for

My question pertains to the interceptor(responseError) of $resource. It is essential to note that I am working with angularjs version V1.3.6. The Issue: app.factory('authInterceptor',['$q', '$location', '$log', fun ...

What is the best way to incorporate buttons that trigger PHP scripts within a MySQL database?

I have a MySQL database filled with various records that I've displayed in an HTML table on a webpage. I want to add two buttons next to each record, both of which trigger PHP scripts. For example, let's say the table lists the names of three pe ...

Printed plaintext of CSS & jQuery code on the 200th iteration in PHP

I encountered an issue while working on a script that involved displaying query data based on domain type (referred to as typeX & type Y). To achieve this, I utilized the jQuery slidetoggle function along with some CSS. Everything was functioning perfectly ...