Unable to manipulate JQuery lightSlider slides using element index

I've been working on a new page design at this link:

The code is still a work in progress, so bear with me as I test out some functions and scripts.

At the end of the first section, there are 4 logos that, when clicked, will trigger a modal to pop up with a slider (using JQuery lightSlider).

I'm encountering console errors when trying to make the slider display the correct slide number corresponding to the logo clicked. The function to get the child number is working fine using .index(this) + 1);, but displaying "index+1 slide" only works once before throwing an error saying 'Uncaught TypeError: Cannot read property 'goToSlide' of undefined.'

Any ideas on how to resolve this issue? I have considered resetting the slider.goToSlide(slide_n); function, but I'm unsure how to do that.

Thank you in advance for any insights!


$(".design-logos").click(function() {

        var slide_n = ($('.design-logos').index(this) + 1);
        

        if ($("#light-slider").hasClass("lightSlider")) {
            
        } else {
            var slider = $("#light-slider").lightSlider({
                item: 1,
                loop: true,
                speed: 1,
                enableDrag: false,
            });
        }     

        slider.goToSlide(slide_n);


Answer №1

Your code appears to be quite messy. I have made several changes in hopes that it will function properly when you replace your existing code in the fourth <script></script> tag on your page with the following code:

var slider;
            $(document).ready(function() {


            // modal in // 

            function modalIn() {

                $(".jp-modal-wrapper").show();
                $('body').addClass("body-ovf");

                setTimeout(function() {

                    $(".projects-main-slider").addClass("projects-main-slider-in");

                    $('.blackdrop').addClass("blackdrop-in");

                    setTimeout(function() {
                        $('.jp-inner-modal').addClass("jp-inner-modal-in");
                    }, 350);

                    $('.carousel-item.active img').lazy({
                        effect: "fadeIn",
                        effectTime: 1000,
                        threshold: 0
                    });

                }, 10);

            };


            // modal off //

            function modalOff() {

                $('.jp-inner-modal').removeClass("jp-inner-modal-in");

                setTimeout(function() {
                    $('.blackdrop').removeClass("blackdrop-in");
                }, 500);

                setTimeout(function() {
                    $(".jp-modal-wrapper").hide();
                    $('body').removeClass("body-ovf");
                }, 1000);

            };

            $(".blackdrop").click(function() {
                modalOff();
            });

            $('body').keydown(function(e) {
                if (e.keyCode == 27) {
                    modalOff();
                }
            });

            // modal off //
            
                

            $(".design-logos").click(function() {

                var slide_n = ($('.design-logos').index(this) + 1);                
                

                // modal in //                     
                modalIn();

                setTimeout(function() {


                    if ($("#light-slider").hasClass("lightSlider")) {
                        
                    } else {
                        slider = $("#light-slider").lightSlider({
                            item: 1,
                            loop: true,
                            speed: 1,
                            enableDrag: false,
                        });
                    }

                                  
                    setTimeout(function() {     
                    slider.goToSlide(slide_n);

                }, 301);

                //else

            }, 5);

            function fadeSlideIn() {
                    $(".next").addClass("disable-button");
                    $(".projects-main-slider").addClass("projects-main-slider-mov");
            }

                function fadeSlideOut() {
                    $(".next").removeClass("disable-button");
                    $(".projects-main-slider").removeClass("projects-main-slider-mov");
                }

                $(".gotoslide").click(function () {

                    slider.goToSlide(2);
                });





            $(".next").click(function () {
                    fadeSlideIn();
                    const curSliderInd = slider.getCurrentSlideCount();
                    const nextSlide = curSliderInd == 4 ? 1 : curSliderInd + 1;
                    setTimeout(function () {
                        let curSliderInd = slider.getCurrentSlideCount();
                        slider.goToSlide(nextSlide);
                    }, 301);
                    setTimeout(function () {
                        fadeSlideOut();
                    }, 302);
            });

            $(".prev").click(function () {
                    fadeSlideIn();
                    const curSliderInd = slider.getCurrentSlideCount();
                    const nextSlide = curSliderInd == 1 ? 4 : curSliderInd - 1;
                    setTimeout(function () {
                        
                        slider.goToSlide(nextSlide);
                    }, 301);
                    setTimeout(function () {
                        fadeSlideOut();
                    }, 302);
                });
            });






        });

Feedback on your code:

Firstly, the reason your code was not working is because the else block condition:

if ($("#light-slider").hasClass("lightSlider")) {
            
        } else {
            var slider = $("#light-slider").lightSlider({
                item: 1,
                loop: true,
                speed: 1,
                enableDrag: false,
            });
        }

is only executed if the element light-slider does not already have the class lightSlider, which happens when one of the logos is clicked for the first time. However, declaring slider within this block causes it to become undefined if the else block is not initially executed. Providing slider with a global reference resolves this issue. Although this solution is not ideal, it was implemented due to time constraints.

Secondly, I noticed unexpected behavior with the goToPrevSlide() and goToNextSlide() methods after testing your page extensively. Therefore, I modified the calls to these methods within the callbacks of the next and prev buttons.

Lastly, some of your callback function definitions were placed inside a setTimeout unnecessarily! This may have been done inadvertently, but I have removed them regardless. There are other formatting issues present that I did not address, so you may want to correct those as well to prevent any future complications.

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

Can a JavaScript function be sent back via AJAX from PHP?

Can a javascript function be returned via Ajax from php? Typically, I would just return a value and handle it in plain javascript. However, since I am working on an Apache Cordova mobile app, I need to approach things differently. account = localStorage.g ...

What is the most effective way to receive all values sent to an Observer upon a new subscription?

I have an observer that receives various values emitted to it at different times. For instance sub = new Subject<any>(); sub.next(1); sub.next(2); sub.next(3); #hack 1 sub.next(4); sub.next(5); sub.next(6); #hack 2 If there is a ...

using conditional statements in an app.get() method in express js

app.get('/api/notes/:id', (req, res, next) => { fs.readFile(dataPath, 'utf-8', (err, data) => { if (err) { throw err; } const wholeData = JSON.parse(data); const objects = wholeData.notes; const inputId ...

HTML5 allows users to play a extended video for a set duration without the need for any video editing. Users are encouraged to utilize any approach

I have a video file named myvideo.mp4 that is 3 minutes long (or any length). <video width="320" height="240" controls="controls"> <source src="myvideo.mp4" type="video/mp4"> </video> Is there a way to play this myvideo.mp4 for only 20 ...

Effective strategies for minimizing the bundle size of your NextJs application

Recently, I launched my first NextJS app and was surprised to see that the initial bundle size is around 1.5Mb, which seems quite large for me as a beginner in using Nextjs. I have shared an image of the yarn build and also my package.json. All the pages ...

Is it possible to determine which child element is currently in view within a scrollable parent div?

In an attempt to replicate a "current page" feature using divs, similar to a PDF reader. document.addEventListener("DOMContentLoaded", function(event) { var container = document.getElementById("container"); container.onscroll = function() { let ...

Issue with Express.js res.append function: Headers cannot be set after they have already been sent

I encountered an issue in my express project where I tried to set multiple cookies using "res.append" in the same request, but I kept getting an error saying "Error: Can't set headers after they are sent.". Can someone help me identify the problem and ...

"Interactive functionality: Toggling checkboxes with a DIV click

I am trying to set up a simple div container that displays contact information in a formatted list (<ul><li>). Clicking on the div currently takes you to the user's profile page, which is functioning correctly. However, I am facing an iss ...

Issues encountered when trying to use ng-repeat alongside a multiselect plugin

<select class="form_control" id="district" name="district" multiple ng-model="$scope.district"> <option value="{{tp_id}}" ng-repeat="tp_id in district" >{{tp_id}} </option> </select> I am facing an issue where no v ...

Exploring tailored markup features in Next.js version 13

I am trying to optimize my website for social media sharing on platforms like WhatsApp. I have been experimenting with different methods to set custom markup in Next.js 13, but haven't achieved the desired outcome yet. Your help and insight are greatl ...

React and D3 Force Layout: uncharted territories for new links' positions

After carefully following the general update pattern for new React Props, I've noticed that D3 efficiently handles data calculation and rendering when receiving new props. This prevents React from having to render every tick. D3 functions seamlessly ...

Place two divs side by side with the second div filling up the remaining space on the line

Hello there, can anyone lend a hand with this problem? This is the code I have been working with: <html> <body> <div style="width=100%"> <div style="float:left; background-color:Red; height:100px">Red</div> <div st ...

Create visual representations using the data displayed in charts generated by Chart JS

Good evening. I am currently utilizing Chart JS in my project to visualize the total count per column in a bar graph. My backend framework is Laravel, and I pass the data from the controller using the variable $datacount. This snippet shows the query in ...

What is the term used to describe the way console.log styles the Json object?

Have you ever noticed that when a JSON object is printed, say in a script run by node using console.log, it doesn't exactly pretty print the JSON? It sort of strikes a balance between showing as few lines as possible while still maintaining readabilit ...

SOLVED: NextJS restricts plugins from modifying HTML to avoid unnecessary re-rendering

My current scenario is as follows: I am in the process of developing a website using NextJS (SSR) I have a requirement to load a script that will locate a div element and insert some HTML content (scripts and iframes) within it. The issue at hand: It se ...

Angular: displaying dates in a specific format while disregarding time zones

Is there a way to format date-time in Angular using DatePipe.format() without converting timezones, regardless of location? For instance, for various examples worldwide (ignoring time differences) I would like to obtain 07/06/2022: console.log('2022-0 ...

Retrieve data from the table and dropdown menu by clicking a button

A script is in place that retrieves data from two columns (Members, Description) dynamically from the table upon button click. Table html Here is the JQuery code responsible for extracting values from the table: $(function() { $('#myButton') ...

Discover the seamless integration of using Angular UI select2 with Angular 1.2.5 for a smooth user

I am attempting to make this jsfiddle compatible with angular 1.2.5 instead of just 1.0.5. http://jsfiddle.net/hWXBv/25/ <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script> The goal is to create a Gmail-lik ...

Searching through a JSON object on a Laravel web page using JavaScript or AJAX for live filtering purposes

After diving into AJAX and JavaScript, I find myself needing to replace some outdated Angular functionality on our Laravel site. The specific task at hand is creating a live search filter for a page with a static header search bar. The main requirement is ...

Is it possible to modify a portion of the zod schema object according to the value of a

My form consists of several fields and a switch component that toggles the visibility of certain parts of the form, as shown below: <Field name="field1" value={value1} /> <Field name="field2" value={value2} /> &l ...