What steps can be taken to repair the script?

https://jsfiddle.net/fnethLxm/10/

$(document).ready(function() {
    parallaxAuto()
});
function parallaxAuto() {
    var viewer       = document.querySelector('.viewer.active'),
    frame_count  = 5,
    offset_value = 500;

    // init controller
    var controller = new ScrollMagic.Controller({
      globalSceneOptions: {
        triggerHook: 0,
        reverse: true
      }
    });

    // build pinned scene
    var scene = new ScrollMagic.Scene({
      triggerElement: '#sticky',
      duration: (frame_count * offset_value) + 'px',
      reverse: true
    })
    .setPin('#sticky')
    //.addIndicators()
    .addTo(controller);

    // build step frame scene
    for (var i = 1, l = frame_count; i <= l; i++) {
      new ScrollMagic.Scene({
          triggerElement: '#sticky',
          offset: i * offset_value
        })
        .setClassToggle(viewer, 'frame' + i)
        //.addIndicators()
        .addTo(controller);
    }

    $(".right_arrr").click(function(){
        var block = $(this).siblings('.secondSlider');
        el = block.find(".active");
        elNum = el.attr("data-num");
        if(elNum < block.find('.slide').length) {
            elNum++;
        } else {
            elNum=1;
        }
        hideShow(elNum, block);
        alert('slide №' + elNum)
        scene = scene.destroy(true);
        scene = null;
        controller.destroy(true);
        controller = null;
        parallaxAuto();
    });
    $(".left_arrr").click(function(){
        var block = $(this).siblings('.secondSlider');
        el = block.find(".active");
        elNum = el.attr("data-num");
        if(elNum > 1) {
            elNum--;
        } else {
            elNum=block.find('.slide').length;
        }
        hideShow(elNum, block);
        scene = scene.destroy(true);
        scene = null;
        controller.destroy(true);
        controller = null;
        parallaxAuto();
    });
    function hideShow(num, block) {
        block.find("div.active").removeClass("active").animate({ opacity: 0,},300);
        block.find("div.slide"+num).addClass("active").animate({ opacity: 1,},300);
    }
};

You can observe that the plugin works fine on slides 1 and 2, but encounters issues on slide 3 with an error message "Cannot read property 'destroy' of null". I have been trying to solve this issue for a few days now but cannot figure out how to fix it. Any suggestions?

Answer №1

There are 2 key issues that need attention:

  • Resetting the scene and controller to null with every right or left click, requiring a re-initialization of each by recalling parallaxAuto;
  • Each time parallaxAuto is called, the listeners are rebound.

To address this, I have made some adjustments for you so that the listeners are only bound once: https://jsfiddle.net/j6u6wp7x/. I took the liberty of isolating the section where the controller and scene are re-initialized so you can simply call it at the end of the click event without having to re-bind the events.

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

restructure array upon alteration of data

Here's the current structure of an array stored in a $scope variable: $scope.objects: [ {selected: true, description: 'string1'}, {selected: false, description: 'string2'}, {selected: true, description: 'string3'}, ...

Tips for updating server-side variables from the client-side in Next.js

There is a code snippet in api/scraper.js file that I need help with. const request = require("request-promise"); const cheerio = require("cheerio"); let url = "https://crese.org/distintivo-azul/"; let result; request(url, ...

Is "Invalid Date" indicating an incorrect date?

Have you ever wondered why JavaScript returns 'Invalid Date' when setting an (invalid) date? It can be quite confusing and make it difficult to handle errors. So, what is the optimal way to deal with this issue? One approach is to check the date ...

The requestify Node module encounters issues when the body contains special characters

My current project involves the use of node.js and a library called requestify. Here is the snippet of code causing some trouble: console.log('body'); console.log(body); return new Promise(function (f, r) { requestify.request(myurl, { ...

Sharing data between two PHP pages via an AJAX request

On my webpage, specifically on page 1.php, I am saving a variable to an input field text. Name:abc Done. After clicking the 'done' button, the name abc is sent to another page called 2.php via an Ajax request. In 2.php, I am storing the value ...

Exploring asynchronous data handling in AngularJS using promises

Currently, I am working on a single page application using angularJS and encountering some difficulties in storing asynchronous data. In simple terms, I have a service that contains my data models which are returned as promises (as they can be updated asy ...

Adding or Deleting Rows from Input Table

I'm in the process of creating a website that features an input table allowing users to easily add or remove rows at their discretion. The desired UI is shown below: https://i.sstatic.net/EFAlM.jpg Here is the HTML code I have developed so far: & ...

Performing an Ajax request to submit a form without the need to reload the page in MVC

I am looking for assistance with submitting a form from an MVC view without refreshing the page. However, it seems that my AJAX code below is not functioning properly: //here is ajax call function AjaxCallAndShowMessage(btnClick) { $('form').s ...

What is the best way to incorporate React hooks into a for loop?

I am looking to dynamically append a container with a specified number of div elements based on the data in a JSON file. I attempted to include the logic within a for loop, but encountered errors in the process. If you're interested in checking out t ...

Lack of animation on the button

Having trouble with this issue for 48 hours straight. Every time I attempt to click a button in the top bar, there is no animation. The intended behavior is for the width to increase and the left border color to change to green, but that's not what&ap ...

AngularJS service failing to deliver promised result

I am in the process of retrieving data from my database using AngularJS. I have created a service to fetch the data and a controller to display it. Check out my code snippet: angular.module('myApp') .factory('panelService', [&apos ...

The index declaration file has not been uploaded to NPM

After creating a Typescript package and publishing it on NPM, I encountered an issue with the declaration files not being included in the published version. Despite setting declaration: true in the tsconfig.json, only the JavaScript files were being publis ...

Using Node.js to implement GET, POST, and DELETE functionalities

I have embarked on the journey of learning Node.js and I find myself in a state of confusion. Could you please guide me on how to construct effective HTTP requests for the following scenarios: 1) Retrieve all galleries from the gallerySchema using a GET ...

Strategies for Resolving Table Alignment Problems using HTML and JavaScript

I am struggling to figure out how this dashboard will function as it is not a live website, but rather a tool that pulls data from a chemical analysis program and displays it in a browser view. My main issue is aligning two tables at the top of the page ...

Tips for avoiding the exposure of full user models in the jade template

As I work on the login functionality of my project, I'm utilizing express, passport-local, and mongoose. My code includes a series of routes: module.exports = function (app) { app.get('/', function (req, res) { res.render(' ...

"Encountered an error while trying to define a Boolean variable due

I am in the process of creating a TF2 trading bot with price checking capabilities. I encounter an issue while trying to define a boolean variable to determine if the item is priced in keys or not. My attempt at replacing isKeys with data[baseName].prices ...

Work with JSON array objects

I am a novice in javascript and JSON. I have a requirement to process each JSON object, as shown in the example prototype below. Can someone please assist me in solving this problem? I need to log each room number given in the JSON sample below. How can I ...

Utilize the v-if directive with nested object properties for dynamic conditional rendering

I need to verify if the item object has a property called 'url' set. If it's not present, I would like to display a placeholder image. Here is an example of what I want to achieve: <img v-if="item.relationships.main ...

Is it acceptable to initiate an import with a forward slash when importing from the root directory in Next.js?

I've noticed that this import works without any issues, but I couldn't find official documentation confirming its validity: // instead of using a complex nested import like this import { myUtil } from '../../../../../lib/utils' // this ...

Retrieve dynamic data for Pivot in Devexpress AngularJS

I am currently working on an AngularJS web app where I am implementing a Pivot using devexpress, specifically utilizing the Field Chooser. You can find the example code here: In the provided example, static data is used. However, I need to fetch data dyna ...