The variable referencing an unidentified function has not been defined

I've created an anonymous function assigned to a variable in order to reduce the use of global variables. This function contains nested functions for preloading and resizing images, as well as navigation (next and previous). However, when I try to run the code, I'm getting this error message: Cannot read property 'preload_and_resize' of undefined If you can help me identify the issue, I would greatly appreciate it. Thank you!

<html>
<head>
<script type="text/javascript">
var myFunction=(function(){
 var myImages=new Array("img/01.jpg","img/02.jpg","img/03.jpg");
 var imageObj = new Array();
 var index=0;
 var preload_and_resize=function(){
        var i = 0;
        var imageArray = new Array();
        for(i=0; i<myImages.length; i++) {
            imageObj[i] = new Image();
            imageObj[i].src=myImages[i];
        }

    document.pic.style.height=(document.body.clientHeight)*0.95;
};
 var next_image=function(){
    index++;
    if(index<imageObj.length){
        document.pic.src=imageObj[index].src;
    }
    else{
        index=0;
        document.pic.src=imageObj[index].src;
    }
 };
 var prev_image=function(){
    index--;
    if(index>=0){
        document.pic.src=imageObj[index].src;
    }
    else{
        index=myImages.length-1;
        document.pic.src=imageObj[index].src;
    }
 };
})();
</script>
</head>
<body onload="myFunction.preload_and_resize();">
<div align="center">
<img name="pic" id="pic" src="img/01.jpg"><br />
<a href="JavaScript:myFunction.prev_image()">Prev</a><a href="JavaScript:myFunction.next_image()">Next</a>
</div>
</body>
</html>

Answer №1

Your specific function is not returning any value, so when executed, it will return undefined. Hence, the runThisCode object remains undefined as well. Additionally, given your current setup, the preload_and_resize function will be limited to local scope and cannot be accessed externally.

To address this issue, consider modifying your anonymous function to construct an object and return it instead. The following code snippet should help guide you in the right direction:

var runThisCode=(function(){
 var result = {};
 result.myImages=new Array("img/01.jpg","img/02.jpg","img/03.jpg");
 result.imageObj = new Array();
 result.index=0;
 result.preload_and_resize=function(){
        var i = 0;
        var imageArray = new Array();
        for(i=0; i< result.myImages.length; i++) {
            imageObj[i] = new Image();
            imageObj[i].src=myImages[i];
        }

    document.pic.style.height=(document.body.clientHeight)*0.95;
};
 result.next_image=function(){
    index++;
    if(index<imageObj.length){
        document.pic.src=imageObj[index].src;
    }
    else{
        index=0;
        document.pic.src=imageObj[index].src;
    }
 };
 result.prev_image=function(){
    index--;
    if(index>=0){
        document.pic.src=imageObj[index].src;
    }
    else{
        index=myImages.length-1;
        document.pic.src=imageObj[index].src;
    }
 };

 return result;
})();

Answer №2

Here is a breakdown of your mistake:

let example = (function (){
   let privateVar1, privateVar2 = 'sum' , etc;
   return {
      publicFunction: function() {},
      anotherFunction: function() {
          console.log('cogito ergo ' + privateVar2 );
      }
   };

})();

example.anotherFunction();

Answer №3

In order for the code to function properly, you have assigned the function to the variable next_image, which is contained within a self-invoking anonymous function.

The value that you are assigning to runThisCode is actually the result of that anonymous function, and since there is no return statement, it defaults to undefined.

To make this code work as intended, you should assign an object to runThisCode and ensure that next_image is a property of that object.

Make sure to include the following at the end of the anonymous function:

return {
    "next_image": next_image
}

Answer №4

To enhance the functionality of your function, eliminate the anonymous element and ensure it is public. The only global variable required is the object called runThisCode.

var runThisCode = function () {
    var myImages = new Array("img/01.jpg", "img/02.jpg", "img/03.jpg");
    var imageObj = new Array();
    var index = 0;
    this.preload_and_resize = function () {
        var i = 0;
        var imageArray = new Array();
        for (i = 0; i < myImages.length; i++) {
            imageObj[i] = new Image();
            imageObj[i].src = myImages[i];
        }

        document.pic.style.height = (document.body.clientHeight) * 0.95;
    };
    this.next_image = function () {
        index++;
        if (index < imageObj.length) {
            document.pic.src = imageObj[index].src;
        } else {
            index = 0;
            document.pic.src = imageObj[index].src;
        }
    };
    this.prev_image = function () {
        index--;
        if (index >= 0) {
            document.pic.src = imageObj[index].src;
        } else {
            index = myImages.length - 1;
            document.pic.src = imageObj[index].src;
        }
    };
};

Then, at a later stage in your code:

runThisCode.preload_and_resize();

will be effective.

Answer №5

It appears that the intention behind the IIFE (immediately invoked function expression) in your body onload property is to create an object with a method named preload_and_resize.

However, it seems that you are not actually returning anything from the IIFE. This means that everything inside the IIFE is encapsulated within its own namespace without being "exported."

If you wish to export these functions from the IIFE, you could include a return statement at the end like this:

return {
    'preload_and_resize': preload_and_resize,
    'next_image': next_image,
    'prev_image': prev_image
}

This code snippet creates a new JavaScript object literal and assigns the function values from the local scope to its properties.

While some developers might find this type of explicit export redundant, others may prefer defining the functions within the object literal declaration like so:

return {
    preload_and_resize: function(){
        // Function logic for preloading and resizing images
    },
    next_image: function() {
        // Function logic for displaying the next image
    },
    prev_image: function() {
        // Function logic for displaying the previous image
    }
}

Answer №6

Here is my take on the previous answers:

const imageSlider = (function(self) {
    let images = new Array("img/01.jpg", "img/02.jpg", "img/03.jpg");
    let imageObjects = new Array();
    let index = 0; 

    self.preloadAndResize = function() {
        let i = 0;
        let imageArray = new Array();
        for (let i = 0; i < images.length; i++) {
            imageObjects[i] = new Image();
            imageObjects[i].src = images[i];
        }
        document.pic.style.height = (document.body.clientHeight) * 0.95;
    };
  
    var nextImage = function() {
        index++;
        if (index < imageObjects.length) {
            document.pic.src = imageObjects[index].src;
        } else {
            index = 0;
            document.pic.src = imageObjects[index].src;
        }
    };
  
    var prevImage = function() {
        index--;
        if (index >= 0) {
            document.pic.src = imageObjects[index].src;
        } else {
            index = images.length - 1;
            document.pic.src = imageObjects[index].src;
        }
    };
})(window.myCurrentPage = window.myCurrentPage || {});

// You can now call myCurrentPage.preloadAndResize();

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

Retrieving information from a JSON web service can easily be done using just JavaScript and jQuery

I recently downloaded a sample application from the following URL: . I am pleased to report that the part I have implemented is functioning flawlessly: <script src="scripts/jquery-1.3.2.debug.js" type="text/javascript"></script> <script src ...

Execute various settimeout or display functions on various elements of a webpage

Just a heads up, I'm not really experienced in development. More on the newbie side of things, but eager to learn. I've been looking for an answer to my question, but so far haven't come across anything that fits my specific situation. It m ...

What is the process for incorporating the !important declaration into a CSS-in-JS (JSS) class attribute?

I'm currently exploring the use of CSS-in-JS classes from this specific response in conjunction with a Material UI component within my React project. In order to override the CSS set by Bootstrap, I've decided to utilize the !important modifier. ...

What is the best method for performing cross-domain queries utilizing ajax and jsonp?

When attempting to send an ajax request to a specific URL, I encountered an error. Below is the code I used: $.ajax({ url: "http://webrates.truefx.com/rates/connect.html?q=ozrates&c=EUR/USD&f=csv&s=n", dataType : 'jsonp', ...

Encountering a 404 error while accessing my meticulously crafted express server

After ensuring that the server is correctly set up and without any errors related to imports or missing libraries, I utilized cors for development purposes. A 404 error persisted even after attempting to comment out the bodyparser. https://i.stack.imgur.c ...

I want to add an LI element to a UL by utilizing jQuery in forms.js

I have several forms on my webpage and I am utilizing jQuery form.js to save each comment that users post. After saving the comment successfully, I want to append it to the UL tag. Although the saving part is functioning properly, I am encountering difficu ...

How to incorporate both image and text links within an HTML div container using JavaScript

I am trying to create a clickable image and text within a div named "films" that both link to the same webpage. However, I am experiencing an issue where only the text link works and the image link is disabled. If I remove the text link, then the image l ...

Is it safe to utilize an AngularJS filter for parsing a URL?

When working on a web application, my client-side (angularjs based) receives JSON data from a web service. The JSON can contain a text field with some URLs, such as: blah blah ... http://www.example.com blah blah blah ... To render these links as HTML, I ...

Exploring outside iframe data

My webpage includes an iframe A with a src attribute that links to a URL containing another embedded iframe B. I'm trying to figure out if it's possible to access the src of this nested iframe B. However, it appears that browser security measures ...

Can Javascript be used to obtain someone's UDID?

Is it feasible to retrieve individuals' UDIDs when they visit your website? If this is achievable, could you recommend a helpful tutorial for me to follow? ...

Eliminate the alert message that appears when dynamically rendering a React styled component

When checking the browser console, I noticed a warning that reads as follows: react_devtools_backend.js:3973 The component styled.div with the id of "sc-dmRaPn" has been created dynamically. You may see this warning because you've called sty ...

What is the best method for translating object key names into clearer and easier to understand labels?

My backend server is sending back data in this format: { firstName: "Joe", lastName: "Smith", phoneNum: "212-222-2222" } I'm looking to display this information in the frontend (using Angular 2+) with *ngFor, but I want to customize the key ...

View a pink map on Openlayers 2 using an iPhone

I am currently working on a project where I am trying to track my location using my smartphone and display it on a map. To achieve this, I am utilizing openlayers 2. However, I am encountering an issue. When I implement the code below in a Chrome Browser ...

Using jQuery each with an asynchronous ajax call may lead to the code executing before the ajax call is completed

In my jQuery script, I utilize an each loop to iterate through values entered in a repeated form field on a Symfony 3 CRM platform. The script includes a $.post function that sends the inputted value to a function responsible for checking database duplicat ...

What is the best way to generate an array of objects by extracting specific properties from another array object?

Here is the information provided: const cocktail = [ { "idDrink":"13070", "strDrink":"Fahrenheit 5000", "strGlass":"Shot glass", "strInstructions":&qu ...

Is there a way to shorten the length by left-clicking and increase it by right-clicking?

Illustration: section.my{margin: 20px;} <section class="my"></section> Hover over: section{padding: 10px;} Double click: section{border: 1px solid black;} ...

How can I set the background of specific text selected from a textarea to a div element?

Is it possible to apply a background color to specific selected text from a Text area and display it within a div? let elem = document.getElementById("askQuestionDescription"); let start = elem.value.substring(0, elem.selectionStart); let selection = ...

Getting URL parameters in NextJS when using Custom Document can be achieved by accessing the `ctx`

Currently, I am utilizing NextJS for generating SSR pages that are language-specific. I want to specify the lang property to indicate the language of the text. Here's what I have done so far: import Document, { Html, Head, Main, NextScript } from &qu ...

AngularJS $http get isn't functioning properly, but surprisingly $.ajax works perfectly

Recently delving into the world of AngularJS, I am facing a hurdle with $http functionality. In my factory setup below: app.factory('employeeFactory', function ($http) { var factory = {}; // Retrieving data from controller var emplo ...

Run JavaScript code whenever the table is modified

I have a dynamic table that loads data asynchronously, and I am looking for a way to trigger a function every time the content of the table changes - whether it's new data being added or modifications to existing data. Is there a method to achieve th ...