Attempting to utilize a for loop in JavaScript to condense code, however encountering a "not defined" error

I'm relatively new to working with javascript and currently attempting to enhance the following code snippet (which has been tested and is functioning correctly):

// snail 1 //
var s1 = document.createElement("div");
s1.id = snail1.id;
s1.className = "snail-container";
s1.style.backgroundImage = "url('" + this.snail1.photo+ "')";
s1.style.top = snail1.y + "px";
s1.style.left = snail1.x + "px";
racetrack.appendChild(s1);

// snail 2 //
var s2 = document.createElement("div");
s2.id = snail2.id;
s2.className = "snail-container";
s2.style.backgroundImage = "url('" + this.snail2.foto + "')";
s2.style.top = snail2.y + "px";
s2.style.left = snail2.x + "px";
racetrack.appendChild(s2);

... ... ...

and so forth... (4 in total)

My goal is to convert this into a for loop that can accommodate more instances as needed, however, I keep encountering the error: Uncaught ReferenceError: snail is not defined at window.onload (racerevision.js:138) when I implement the following code:

for(var i = 1; i < 5; i++)
    {
        var s1 = document.createElement("div");
        s1.id = snail+i.id;
        s1.className = "snail-container";
        s1.style.backgroundImage = "url('" + this.snail.photo+ "')";
        s1.style.top = snail+i.y + "px";
        s1.style.left = snail+i.x + "px";
        racetrack.appendChild(s1);
    }

Can you help me identify where my mistake lies in this implementation?

Answer №1

There seems to be an issue with snail+i.x, please correct it to this["snail"+i].x (to access snail1, snail2, etc.) and do the same for similar instances throughout the code:

for(var i = 1; i < 5; i++)
    {
    var s1 = document.createElement("div");
    s1.id = this["snail"+i].id;
    s1.className = "snail-container";
    s1.style.backgroundImage = "url('" + this.snail.photo+ "')";
    s1.style.top = this["snail"+i].y + "px";
    s1.style.left = this["snail"+i].x + "px";
    racetrack.appendChild(s1);

    }

Answer №2

To maintain a record of your snails along with their characteristics, it is recommended to use either an array or an object literal, and then loop through it to generate those components.

Here is a potential approach:

var racetrack = document.getElementById("racetrack");

// defining the "map" containing all snails and their attributes
var snails = {
  "1": {
    id: 1,
    photo:
      "https://image.shutterstock.com/image-vector/vector-illustration-snail-cartoon-260nw-187683554.jpg",
    y: 10,
    x: 10
  },
  "2": {
    id: 2,
    photo:
      "https://image.shutterstock.com/image-vector/vector-illustration-snail-cartoon-260nw-187683554.jpg",
    y: 20,
    x: 20
  },
  "3": {
    id: 3,
    photo:
      "https://image.shutterstock.com/image-vector/vector-illustration-snail-cartoon-260nw-187683554.jpg",
    y: 30,
    x: 30
  },
  "4": {
    id: 4,
    photo:
      "https://image.shutterstock.com/image-vector/vector-illustration-snail-cartoon-260nw-187683554.jpg",
    y: 40,
    x: 40
  }
};

for (var i = 0; i < Object.keys(snails).length; i++) {
  var s = document.createElement("div");
  var snail = snails[i + 1]; // retrieving snail's properties from the "map"

  s.id = snail.id;
  s.className = "snail-container";
  s.style.backgroundImage = "url('" + snail.photo + "')";
  s.style.top = snail.y + "px";
  s.style.left = snail.x + "px";

  racetrack.appendChild(s);
}
.snail-container {
  width: 130px;
  height: 95px;
  background-size: cover;
  margin-bottom: 15px;
}
<div id="racetrack"></div>

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

Is it better to store CSS and JavaScript in separate files or within the main HTML document

While the best practice is to place JavaScript and CSS code in separate files (such as .js and .css), many popular websites like Amazon, Facebook, etc. often include a large portion of their JavaScript and CSS code directly within the main HTML page. Whic ...

Move content off the screen using CSS3 translation

Throughout various projects, I have encountered the need to make elements on a webpage translate out of view (essentially making them fly out of the document). The idea was that by simply adding a class to the element, the CSS would take care of the animat ...

The canvas loadFromJson function fails to implement the font-family property

I have implemented the following code to display Google font and update the canvas: /* on change of font, load the preview and update the canvas */ $('#font').on('change', function () { $('.font_preview').show ...

`How can I effectively integrate react-i18next with the Semantic UI label element?`

Currently, I am working with Semantic UI along with the integration of [react-i18next][2]. My goal is to enable translation for label strings, but these labels include HTML tags, such as span. Unfortunately, the system only allows hardcoded or variable s ...

Encountering issues with the Sequelize Model.prototype.(customFunction) feature malfunctioning

While attempting to define a customFunction within the Sequelize model, I encountered an error: TypeError: user.getJWT is not a function at User.create.then (/projects/test/a/app/controllers/UserController.js:22:29) Below is the code snippet from ...

Steps to implement an image zoom function triggered by a button click

I'm working on a school project that requires me to use only html, css, and javascript for creating a website. Currently, I'm designing a landing page with a button that will navigate the user to another page. My goal is to have the background im ...

Troubleshooting a Basic jQuery Validation Problem

I've been attempting to incorporate the "Refactoring rules" segment from http://jqueryvalidation.org/reference/ However, I'm struggling to figure out the appropriate placement for the $.validator code. Currently, I'm inserting it like this: ...

Clickable link in popup window using fancybox

When I try to use fancybox to open an iframe and scroll to an anchor tag, it works perfectly in IE but not consistently in other browsers. It stops at a different place than the anchor. I suspect the issue may be related to JavaScript based on information ...

Only include unique objects in the array based on a common property

I am currently working with the following array: [ {name: "Mike", code: "ABC123"}, {name: "Sarah", code: "DEF456"}, {name: "John", code: "GHI789"}, {name: "Jane", code: "JKL01 ...

Algorithmically alter the view of the webvr camera

I am looking to dynamically change the position of a view within a webvr scene. My approach involves using the position.add method. Below is the code snippet that demonstrates how I programmatically move the camera: <a-entity position="33 0 -33" rota ...

In Node.js, I encountered an issue where req.body was returning as undefined, despite the fact that when I logged req, I could

I am having trouble logging the req.body to the console in my Twilio text app. When I try console.log(req), the body and its contents show up, but it says that the body is undefined when I try to log it on its own. Any help would be greatly appreciated. ...

Unable to view Chart.js on the second tab

I'm currently working on two different charts for a project - a bar chart and a line chart. The bar chart is displayed on the first tab, while the line chart is on the second tab. Interestingly, the bar chart functions properly, and when I point the l ...

When the page is refreshed, the ContextProvider fails to mount

For the complete code, you can view it on codesandbox. Within my countries API application, I have implemented two Route components - <> <Header/> <Router> <Switch> <CountriesDataProvider> ...

Error with NEXTJS: Prop type failed - The prop `href` in `<Link>` is expecting a `string` or `object`, but received `undefined`

After importing the Link from next/link and attempting to pass the dynamic endpoint in my components, I encountered an error message. https://i.stack.imgur.com/eqUK8.png https://i.stack.imgur.com/eIC4V.png I searched for a solution and came across a sug ...

Identifying the hashKey and selected option in a dropdown menu

My attempt to set the selected option for the select menu is not working because the data in the ng-model that I am sending has a different $$hashKey compared to the data in the select menu, and the $$hashKey holds the values. <select class="form-contr ...

Shade within the autocomplete

Is there a way to make the color property warning work on my autocomplete element at all times, rather than just on focus? Any suggestions or workarounds? Check out this code sandbox for reference. I really want the warning color to be visible constantly ...

"Troubleshooting a Node.js JWT issue in a React.js

I've been diving into backend development and recently created some small APIs. They all function perfectly in Postman, but I encountered an issue when attempting to execute this particular call const onSubmit = async () => { try { setIsL ...

Save the user input to a dedicated text file

I am working with a couple of select tags that generate an array. Previously, I was only logging the array to the console upon pressing the SUBMIT button, but now I want to save it to a separate text file. Here is my main.html code: <form method="POS ...

Struggling with rendering components in REACT?

I'm encountering an issue with rendering the Butcher Shop component. I can't seem to pinpoint what's causing it to be null or undefined. Can someone help me identify the mistake? Nothing is showing up on the DOM and I keep getting this error ...

Issues with arguments not being identified - Discord.js version 14

After discovering that my arguments are no longer being recognized when executing a command, I encountered a strange issue. When args are not included, my console logs undefined, but if args are added, nothing is logged. This is snippet of my command hand ...