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

Ensuring text is perfectly centered within a div, regardless of its length

In the quest to center text of unknown length within a div, challenges arise. Constraints limit its size to a certain extent, making it unclear whether one or two lines will be needed. As such, traditional methods like line-height are not viable options. A ...

Transferring temporary information from server to controller using angular-file-upload

Currently, I am utilizing the angular-file-upload library which can be found at this link: https://github.com/danialfarid/angular-file-upload. In the example provided on that page, data from a file is sent to the backend from a controller using the availab ...

Generating a Vue JS component on the fly

How can I dynamically create a component in Vue JS on click and then route to that component in a single click event? I am using Vue 3 and my current code snippet looks like this: methods:{ routerClick(value){ console.log("The number is "+value) ...

What are the steps to crafting a personalized message for the valid() method in the JOI library?

To validate the property subscription, I use the following method: Joi.object({ subscription: Joi.string() .valid('starter', 'pro', 'business') .required() .messages({ 'string.base': `{{#label}} s ...

Error: Unable to set attribute because the property is undefined in the onLoad function

Can anyone help troubleshoot this error? List of included files: <link rel="stylesheet" href="../../node_modules/semantic-ui/dist/semantic.min.css"> <link rel="stylesheet" href="../../node_modules/font-awesome/css/font-awesome.min.css"> <l ...

The production build of Angular 2 with special effects amplification

I am currently working on an Angular 2 Beta 8 app that I need to bundle and minify for production deployment. Despite configuring the system to generate a Single File eXecutable (SFX) bundle, I am encountering issues with creating a minified version of the ...

Downloading a file through a JavaScript link in HTMLUnit: A step-by-step guide

Looking to download a file with HTMLUnit from a javascript link is proving to be quite challenging. The journey begins at this page. When clicking on the "Authenticate with Java Web Start (new method)" link, a .jnlp file is downloaded, initiating a Java pr ...

inconsistency in button heights

I am currently working on a website project for one of my college courses and I have encountered an issue with the button heights in my slide show not matching up. I'm seeking advice or tips on how to align both buttons to have the same height. Can an ...

An anchor-shaped name tag with a touch of flair

I stumbled upon this unique anchor name design on the website Does anyone here know how to create something similar? What is that style called? ...

Customize CKEditor by automatically changing the font family when the page is loaded

How can I change the font-family of CKEditor to Meiryo based on a JavaScript boolean? I attempted this code in my custom JS within an if condition, but it did not successfully change the font-family: config.font_style = { element : 'span&apo ...

Adding text chips to a text field in Vuetify - A simple guide

I have successfully integrated a text field with vuetify and now I am looking to incorporate chips into it. Currently, chips are only added if the entered text matches a specific pattern (such as starting with '{' and ending with '}'). ...

What is the TypeScript syntax for indicating multiple generic types for a variable?

Currently working on transitioning one of my projects from JavaScript to TypeScript, however I've hit a roadblock when it comes to type annotation. I have an interface called Serializer and a class that merges these interfaces as shown below: interfa ...

Implementing CSS Transform for Internet Explorer

Hello, is there a way to make this function in IE ?? I have been looking into IE transformations but it appears that they are not supported.. Is there an alternative method or something else? It works in other browsers like Firefox, Chrome, and Opera. I s ...

The value stored in $_POST['valuename'] is not being retrieved

Having recently delved into ajax, I am encountering some difficulties in making it function properly. The objective of the code is to send two variables from JavaScript to PHP and then simply echo them back as a string. However, instead of receiving the e ...

What are the steps to implement server side routing using react-router 2 and expressjs?

If you're looking to delve into server side rendering with react-router, the documentation linked here might fall short in providing a comprehensive understanding. In particular, it may not offer enough insights on how to leverage react-router 2 for r ...

Encountering a problem while creating a Page Object in webdriver.io - getting the error "setValue is not a function" or "cannot read property 'setValue' of undefined"

While working on a webdriver.io automation project, I encountered an issue with recognizing objects in my page object file (login.po.js) when calling them in the test spec file (test.spec.js). The error message displayed is LoginPage.username.setValue is n ...

Overcomplicating div elements with unnecessary cloning during checkbox usage

Whenever I check the checkbox and press OK, I want to clone a div with specific user details. Everything works as expected when selecting multiple users. However, adding more users without unchecking the previous checkboxes results in cloned buttons but no ...

populating all available space in layouts using bootstrap columns

I am attempting to create a grid layout using bootstrap, but I am facing an issue with positioning one of the columns. I have tried adjusting the placement of the divs and using offsets/pulls, but so far I have not been successful. To explain what I am a ...

Passing a Ruby session variable to a JavaScript tag: a step-by-step guide

I'm currently collaborating with a vendor who utilizes a JavaScript tag for sale attribution, and I need to pass session variables to the tag. The tag appears to be firing properly, as I can see the variables in the logs, but they aren't reflecte ...

unable to retrieve value from JSON object

It appears that I'm having trouble accessing my object variables, most likely due to a silly mistake on my part. When I console.log my array of objects (pResult), they all look very similar with the first object expanded: [Object, Object, Object, Obj ...