Could you assist me in troubleshooting this basic JavaScript code?

I'm having trouble with my pictures not loading even though they're in the same folder.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Animal</title>
<script type="text/javascript">
var i = 0;
var timeout;
function preLoadImages()
{
if(document.images)
{
animalArray = new Array();
animalArray[0] = new Image();
anmialArray[0] = "bear.jpg";
animalArray[1] = new Image();
anmialArray[1] = "duck.jpg";
animalArray[2] = new Image();
anmialArray[2] = "elephant.jpg";
animalArray[3] = new Image();
anmialArray[3] = "lion.jpg";
animalArray[4] = new Image();
animalArray[4] = "cat.jpg";
}
else
alert("There are no images to load");
}
function startSlideShow()
{
if(i < animalArray.length)
{
document.images["animal_pic"].src = animalArray[i];
i++;
}
else
{
i =0;
document.images["animal_pic"].src = animalArray[i];
}
timeout = setTimeout('startSlideSHow()', 3000);
}
function stopSlideShow()
{
clearTimeout(timeout);
}
</script>
</head>
<body bgcolor="#FFFF00" onLoad = "preLoadImages()">
<img name="animal_pic" height="300" width="300"/>
<form>
<br/><br/>
<input type=button value="Start Show" onClick="return startSlideShow();"/>
<input type=button value="Stop Show" onClick="return stopSlideShow();"/></form>      
</body>
</html>  

Answer №1

The animal array has been created, but the value is incorrectly stored in anmial. Additionally, the src property must be set...

Incorrect:

animal[0] = new Image();
anmial[0] = "bear.jpg";

Corrected version:

animal[0] = new Image();
animal[0].src = "bear.jpg";

Answer №2

Upon a quick glance, it appears that you are missing a closing bracket here :

animal[3] = "lion.jpg";
animal[4] = new Image();
animal[4] = "cat.jpg";
} else {

I also noticed some spelling errors in the name of your array :

anmial[3] = ...
animal[4] = ...

Make sure to tidy up your code before proceeding with testing...

Answer №3

Below is some code I have developed that should be effective:

(function() {

    'use strict';

    var currentImage = 0,
        imageElement,
        timer,
        images = [
            'bear.jpg',
            'duck.jpg',
            'elephant.jpg',
            'lion.jpg',
            'cat.jpg'
        ];

    var startSlideShow = function() {

        timer = window.setInterval(nextImage, 3000);
    };

    var stopSlideShow = function() {

        window.clearInterval(timer);
    };

    var nextImage = function() {

        currentImage++;

        if( currentImage == images.length ) {
            currentImage = 0;
        }

        imageElement.src = images[currentImage];
    };

    window.addEventListener('DOMContentLoaded', function() {

        imageElement = document.querySelector('img[name="animal_pic"]');
        imageElement.src = images[0];

        startSlideShow();
    });

})();

You may want to consider reviewing some fundamental JavaScript tutorials as there are several errors in your code. Here are a few suggestions for improvement.

// Make sure to properly indent your code.
var i = 0;
var timeout;

function preLoadImages() { // This function does not actually preload any images.
    if(document.images) { // Whether or not there are images in the document has no bearing on manually loading them.
        animal = ['bear.jpg', 'duck.jpg', 'elephant.jpg', 'lion.jpg', 'cat.jpg']; // Use array literal notation and declare variables with 'var'.
    } else { 
        alert("There are no images to load"); 
    }
}

function startSlideShow() {
    if(i < animal.length) {
        document.images["animal_pic"].src = animal[i];
        i++;
    } else {
        i = 0;
        document.images["animal_pic"].src = animal[i];
    }
    timeout = setTimeout(startSlideShow, 3000); // Pass the function name directly, and correct the function name typo.
}

function stopSlideShow() {
    clearTimeout(timeout);
}

Answer №4

animal[4] = "cat.jpg";
    }
    else
    alert("There are no images to load");
    }
    function startSlideShow()

It appears that there are two closing curly braces but none to open the else alert( statement. Consider adding an opening curly brace before it:

else
alert("There are no images to load");

You could add an opening curly brace or remove the unnecessary statement altogether.

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

Discover how to utilize a jQuery array using the assistance of a variable

I'm struggling to properly define my question. For each .slider, I have a function and a variable containing "real values" specific to that slider. Since the number of real values varies for each slider, I wanted to determine the number of alternativ ...

In what way does an ArrayList exhibit heterogeneity while utilizing an internal Object[] Array?

Although ArrayList internally uses Object[] Array which is homogeneous, it can still be considered heterogeneous in functionality. Consider the following code snippet that throws an exception when executed: Object[] array = new String[3]; array[0] = "a"; ...

Challenges with Nginx URL redirection

When a page request is made, it goes through the "check.php" process: rewrite ^/(.*)$ http://localhost/check.php?page=$1 The "check.php" file carries out security checks before loading the requested page: <?php // ... security measures requi ...

Modifying a blank array of integers within a ui:repeat loop

I'm attempting to populate the values of an empty integer array using ui:repeat based on inputText entries. Despite following the instructions provided here, my implementation didn't yield the expected results. This is how my UI looks: <ui:re ...

Angular Form Group without a name

Struggling to loop through my formgroups to identify which ones are valid and add the invalid ones to a new array. I can't seem to grab the name value for each formgroup. this.applicationFormArray = new FormGroup({ selectAppFormGroup:th ...

Navigating Date Conversion within Component in Angular 2 Application

Searching for a way to update the display of certain dates in my Angular 2 application, I encountered a roadblock. Using the date pipe in conjunction with string interpolation wasn't viable due to the structure of my template code: <input class="a ...

How can I turn off the animation for a q-select (quasar select input)?

I'm just starting out with Quasar and I'm looking to keep the animation/class change of a q-select (Quasar input select) disabled. Essentially, I want the text to remain static like in this image: https://i.stack.imgur.com/d5O5s.png, instead of c ...

Adding JSON data to an HTML document

Seeking guidance on how to efficiently parse and display information from a JSON file consisting of 3 objects onto a widget. Unsure of the best approach to achieve this task. Any suggestions or methods would be greatly appreciated. Widget Structure: < ...

What is the best way to send a string parameter from an Angular UI to a Node.js backend?

My goal is to transfer a string value from an Angular UI to a Node.js backend API, which will then search in MongoDB using the provided string value as shown below. I am attempting to receive input in enteredValue and pass it on to the http.get call as pa ...

Utilize graphics in three.js for texture recycling

My challenge involves loading the same image in a large number (~ 1000) of two-dimensional shapes using three.js, each shape with different offsets. I came across this demo on the official website and modified it to create my own demo, featuring various s ...

Click on the links to view various captions for a single image, one at a time

My goal is to create an interactive image similar to what can be found at . (Click Play and navigate to page 5 to see the interactive physical exam). While this example seems to use Flash, I am interested in achieving a similar effect using javascript/jQue ...

What's preventing me from using the left click function on my published blog post?

This is my first time creating a blogger template and everything seems to be working correctly. However, I have encountered one problem. For some reason, I am unable to left click on my blog post. I have not installed any right/left click disabler and I&a ...

Can you show me a way to display a dynamically created array component on an Angular2 template html?

One way I've been able to generate dynamic component instances is by choosing from pre-existing components. For instance, @Component({ selector: 'dynamic-component', template: `<div #container><ng-content></ng-conten ...

tips for asynchronously loading cloud endpoints APIs

gapi.client.load('myapi1', 'v1', function() { gapi.client.load('myapi2', 'v1', function() { gapi.client.load('myapi3', 'v1', function() { $rootscope.$broadcast( ...

What is the best way to convert an HTML table into an array of objects?

In my Angular Protractor end-to-end (e2e) tests, I need to perform assertions on an HTML fragment similar to the following: <table> <thead> <tr> <th>Name</th> <th>Age</th> ...

Verify WTForm after dynamic updates to select field options with Jquery

As I work on developing a flask application, I have successfully created a form using WTForms. This form consists of two SelectFields (dropdowns) and a submit button. My goal is to make the dropdowns dynamic - meaning that when the user selects an option f ...

Update an existing item or add a new one if it is not already present

I am attempting to create a functionality similar to canva.com, where users can select images from the sidebar and drop them anywhere in the "div", allowing multiple images with individual positions. However, when I use setState(prevState=>{return [...p ...

What is the best way to prevent elements in the split function from being stored in an array?

Currently, I am attempting to utilize the split() method in Javascript to split elements into an array, a result that I do not desire. My goal is for the elements to be stored as values within an object. var string = "as1234,as5678,as6789"; var result = ...

An error was encountered when attempting to use the 'await' syntax in a useEffect() function that called axios.get()

To avoid using .then(..), I have switched to utilizing await. I am making a call to a function that includes an Axios request and returns the data as response.data after awaiting for it. My functional component has a useEffect that is meant to initialize a ...

Using Jquery to create interactive and dynamic webpage elements

I am struggling with a paragraph containing words in a span that are editable upon clicking. The content needs to be dynamically called, but my current approach is not effective. Can anyone provide a solution or a better way to achieve this? Feel free to ...