Concerning the usage of i values within Javascript loops

As a newcomer to Javascript, I have a basic question. I am attempting to create a for loop where new variables are generated based on the value of i. How can I dynamically change variable names using the i value (without resorting to an array)? For instance, in the code snippet below, my aim is to produce top1, top2, left1, left2, and so on.


var i;

for (i=1; i<3; i++) {

    var top'i'=Math.random(); top'i'=450*top-150;

    var left'i'=Math.random(); left'i'=left*1150;
    
    document.getElementById("image'i'").style.top=top'i'+"px";
    
    document.getElementById("image'i'").style.left=left'i'+"px";

    document.getElementById("image'i'").style.display="block";

}

Answer №1

If you want to position images randomly on a page, you can achieve this using the following JavaScript code snippet:

for (var i=1; i<3; i++) {
    var top = Math.random()*450 - 150,
        left = Math.random()*1150,
        el = document.getElementById("image" + i);
    el.style.top = top + "px";
    el.style.left = left + "px";
    el.style.display="block";
}

Each time this code is run, it will set random positions for specified images on the page.

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

Issue with jQuery AJAX call: When submitting an HTML form, control is not being returned to the calling

I am facing an issue with my HTML form where it is loaded correctly into the DOM through a jQuery ajax call. The problem arises when I submit the form data to a PHP module using another jQuery ajax call. Even though the network traffic shows that the form ...

The PDF file appeared blank after receiving a response from the API using Node.js

When I call a REST API that returns a PDF file, the document appears blank when opened. The console indicates that the data may be corrupted. let url ="API-URL"; var options = { 'method': 'GET', 'url': url ...

Tips on dividing and recycling mongodb connection in Node.js

I am currently troubleshooting the connection to MongoDB using Node.js. The code I have in a file named mongodb.js is as follows: const mongoClient = require('mongodb').MongoClient; const env = process.env.NODE_ENV || 'development'; co ...

Is there a way to transform an Array or Object into a new Object mapping?

When using the map method in JavaScript, it typically returns an Array. However, there are instances where I would like to create an Object instead. Is there a built-in way or a simple and efficient implementation to achieve this? Solutions using jQuery ar ...

Extract specific form data to use in a jQuery.ajax request

Having trouble extracting the current selected value from a dropdown form in AJAX URL. The Form: <form name="sortby"> <select name="order_by" onchange="myFunction()"> <option<?php if(isset($_GET['order_by']) && ...

Having trouble modifying a value in a form and submitting it to the following jsp page

I'm encountering an issue with changing the value in a hidden input element before submitting data to another JSP file (db.jsp) for processing. The value should be different depending on which button is clicked, but it always remains as the default va ...

Support for Chrome in Angular 8

Can someone please advise on the minimum version of Google Chrome that is supported by Angular 8? Additionally, I am looking for a way to prompt users to update their Chrome browser if it doesn't meet the required version. My Angular application seems ...

Learn the best way to efficiently transfer multiple checkbox selections in a single object using AJAX

In my form, I have 4 checkboxes with unique IDs like filter_AFFILIATION_1, filter_AFFILIATION_2, and so on up to 4. My goal is to dynamically send the values of checked checkboxes to the server using an ajax call. Below is the snippet of my code: $(&a ...

Obtaining a URL from a parameter

I have a unique situation with one of my parameters in the routing, as it involves an actual URL. router.get('/api/sitemap/:url', function(req, res) { var url = req.params.url; ... } How can I ensure t ...

Implementing Material UI Slider component to update state upon mouse release, enabling real-time sliding functionality

Is there a way to update the new state only upon mouse release for a Material UI slider, while still allowing real-time tracking of the slide? Material UI offers two events: onChange and onChangeCommitted. The latter gives the desired end result, but the s ...

Tips for ensuring the security of your code in node.js

Here is a snippet from my app.js that deals with managing connections: var connections = []; function removeConnection(res) { var i = connections.indexOf(res); if (i !== -1) { connections.splice(i, 1); } } I make a call to removeConn ...

Diverse behaviors exhibited by an array of promises

I've developed a function that generates an array of promises: async addDefect(payload) { this.newDefect.setNote(payload.note); this.newDefect.setPriority(payload.priority); const name = await this.storage.get(StorageKeys.NAME); ...

Getting a "SyntaxError: Unexpected end of input" error while using jQuery ajax with valid JSON

The PHP response in JSON format shows: {"success":0,"message":"Error: No entityId passed!"} However, my JavaScript code throws an error "SyntaxError: Unexpected end of input". PHP: ... //check if an image id was passed for removal in the POST ...

Managing configuration variables in ExpressJS for various environments

Is it possible to set a variable for different environments when defining the environment? app.configure 'development', () -> app.use express.errorHandler({dumpExceptions: true, showStack: true}) mongoose.connect 'mongodb://xxx:<a h ...

How can we convert milliseconds to the corresponding date and time zone in Java?

1)I am trying to determine the user's timezone and current time using the following code snippets: Calendar currentdate1 = Calendar.getInstance(); TimeZone tz = Calendar.getInstance().getTimeZone(); System.out.println("time zone"+tz); System.out.pri ...

Having trouble sending the selected value from a dropdown list to the server using $.ajax

I am embarking on my first project using JQuery (jquery-3.0.0.min.js) and JavaScript. My goal is to build a straightforward web form that connects to a database through a Web API. The form consists of various input text fields and two select dropdowns. ...

Is there a way to modify a specific item within a useState Array in Reactjs?

Having a useState hook that stores data in the following structure: const [orderData, setOrderData] = useState({ demoData1: '', demoData2: '', demoData3: '', demoArrayData: [{itemName: '', itemNumber: ...

Error message 800A03EA in Windows Script Host encountered while running Express.js script

I'm currently diving into the world of JavaScript development, following along with the guidance provided in the book called "JavaScript Everywhere." The book instructs me to execute the following code: const express = require('express' ...

What are some techniques for styling a field when the div id is not specified?

I need to customize a data field within a table, but I am unable to locate or identify its div ID. Here is the page source: <tbody> <tr> <td style="font-size:12px; text-align:center;" name=""> <div sty ...

Stopping React from re-rendering a component when only a specific part of the state changes

Is there a way to prevent unnecessary re-renders in React when only part of the state changes? The issue I'm facing is that whenever I hover over a marker, a popup opens or closes, causing all markers to re-render even though 'myState' rema ...