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

What is the best way to incorporate Vue.js into a Django project?

We are currently working on a school project that involves creating a complete website using Django and Vue. However, we are facing challenges when it comes to integrating Vue into our Django project. In order to simplify things, we have decided to use Vu ...

Change the size of Jive Addon Tile in a vertical orientation

Seeking assistance with resizing the tile container in an angular application embedded within a Jive tile when the view changes. Any advice on how to tackle this issue? This particular tile is deployed to a Jive Cloud instance using a Jive add-on. ...

Exploring the implementation of the meta robots tag within Joomla 2.5's global settings

Encountering a peculiar issue with Joomla 2.5 and the Meta robots tag. Joomla seems to have a flaw where regardless of the URL, as long as there is a valid article id, it will generate a page. For instance: The id '61' is valid but leads to a ...

Send submitted form field arrays to the database

I am currently developing a sewing management app that includes an order page where users can place multiple orders. However, all orders need to be invoiced with one reference code. On the first page, I collect basic details such as pricing, and on the nex ...

Delete with Express Router

I have created a basic "Grocery List" web application using the MERN stack (Mongo, Express, React, Node). However, I am facing an issue where my DELETE REST command does not execute unless I refresh the page. Here is the code for my event handler and the b ...

Submitting form data using Vue and PHPMailer

I've been encountering an issue with submitting a contact form from a page. After submitting the form, nothing seems to happen. My tech stack includes Vue, Axios, and PHPMailer for handling this functionality. Upon inspecting the network tab, it appea ...

Using JavaScript to fetch elements by their ID along with a button

UPDATE: I have corrected the semi-colons, case sensitivity, and brackets in the code. It functions properly if I eliminate the functions after buttonPARTICULAR! Why is that? UPDATE: Issue resolved. My mistake. Apologies!!! :-Z When I simplify it like thi ...

Experiencing an inexplicable blurring effect on the modal window

Introduction - I've implemented a feature where multiple modal windows can be opened on top of each other and closed sequentially. Recently, I added a blur effect that makes the background go blurry when a modal window is open. Subsequently opening an ...

Retrieving information from AngularJS modal window

Seeking a solution to retrieve data FROM modal to invoking controller, as most examples only cover sending data TO the modal. What is the proper method for achieving this? Here is the form used within the modal: <form class="form-horizontal"> < ...

When using the jQuery datepicker on dynamically generated input fields, the selected date automatically updates the first input field

I am currently integrating date inputs with attached datepicker functionality. The issue I am facing is that when I select a date in the first input and proceed to pick another date in the second or subsequent inputs, the last selected date appears in the ...

The number of subscribers grows every time $rootscope.$on is used

I currently have an Angular controller that is quite simple: angular.controller('appCtrl', function ($scope, $rootScope) { $rootscope.$on('channel.message', function () { // do something here } }); In addition, I have a ...

Error: accessing 'map' property of undefined during API retrieval

I am currently working on a project for a full stack blog site. I have successfully created an API for the back-end and it is functioning properly as I am able to retrieve posts from it. However, when I attempt to iterate through the posts using map, I enc ...

What is the speed of retrieving new data once it has been inserted into a firebase real-time database?

In the midst of developing my personal project using next.js, I've encountered an issue with a component that includes a getstaticprops function. This function scrapes a website and then posts the extracted data to a firebase realtime database. Howeve ...

JavaScript's Array.map function failing to return a value

Here is a snippet of code from an api endpoint in nextJS that retrieves the corresponding authors for a given array of posts. Each post in the array contains an "authorId" key. The initial approach did not yield the expected results: const users = posts.ma ...

A guide to setting defaultValue dynamically in React Hook Form

Presently, I am facing an issue with editing the Product page. The props values are fetched through an API and sent from the parent component. However, I am struggling to set this value to my Datepicker input. This is because the defaultValue function from ...

`Turn a photo into a circular shape by cropping it`

Even though I know that the solution involves using border-radius: 50%, it doesn't seem to be working for my situation. In my code using React/JSX notation, this is how the icon is displayed: <i style={{ borderRadius: '50%' }} className= ...

The catch block is triggered when the dispatch function is called within the try block

It's strange how the code below works perfectly without any errors and records a response once the loginHandler() function is triggered. However, when I include the dispatch function inside the try block after receiving the response, the catch block e ...

What are some techniques for animating SVG images?

Looking to bring some life to an SVG using the jQuery "animate" function. The plan is to incorporate rotation or scaling effects. My initial attempt with this simple code hasn't yielded the desired results: $("#svg").animate({ transform: "sc ...

Is there a way to use node.js to retrieve a video in mp4 format?

My goal is to allow users to download a video from my AWS S3 bucket in MP4 format: app.get("/download_video", function(req,res) { filename = "s3.xxx.amazon.com/bucketname/folder/video_example.mp4"; // I'm unsure about the next steps }); Whil ...

To enhance user experience, consider incorporating a 'Next Page' feature after the completion of every four paragraphs,

Here is a code snippet that can be used to print 'n' number of paragraphs: <% while(rs.next()){ String para=rs.getString("poems"); %> <p> <%=para%> </p> <!-- n number of p tags are printe ...