Define characteristics of object contained within an array

My task involves handling an array of image objects:

var pics = ["pic1","pic2","pic3","pic4","pic5","pic6"]

I'm trying to loop through the array and adjust the style.left value by subtracting 10 from the current value. Here is what I attempted:

for (i = 0; i < 6; i++) { 
pics[i].style.left=pics[i].style.left-10
}

However, my current approach doesn't seem to be effective. Can anyone provide guidance on how I can achieve this?

Answer №1

If you have an array of strings instead of elements, you can easily convert string IDs into elements using the getElementById() method:

for (i = 0; i < 6; i++) { 
    var image = document.getElementById(pics[i]);
    image.style.left=image.style.left-10
}

To enhance your code further, consider the following improvements:

// Use pics.length to dynamically calculate the array length.
// By doing this, any additions or deletions in the future won't require
// manual updating of this loop.
for (i = 0; i < pics.length; i++) { 
    var image = document.getElementById(pics[i]);
    image.style.left=image.style.left-10
}

It's important to ensure that this code is executed only after the DOM is fully loaded to avoid potential issues where getElementById() might return null.

Answer №2

Instead of relying on javascript to solve this issue, you can achieve the desired outcome using pure CSS. Simply assign a shared class to all image elements and add the following styles:

.myImg{
     margin-left: -10px;
}

OR

.myImg{
     transform: translate(-10px, 0px);
}

This will shift the image back by 10px, effectively adjusting the positioning without directly manipulating the JavaScript code. (I assume you are attempting to replicate a similar effect as subtracting -10).

Answer №3

The left property in the style object is only applicable to DOM nodes.

In the provided example, you are working with an array of strings, and even if they were image objects, it still wouldn't work. To create DOM nodes, you can do the following:

var image = document.createElement("img")
image.style.left = "10px"

Remember to always attempt to resolve visual problems using CSS rather than Javascript.

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

The process of merging these two functions involves ensuring that one function does not start until the other has successfully completed its task

A closer look at the two functions in question: const handleSubmit = async (e) => { e.preventDefault(); console.log(songLink) const newSong = { songName, songLink, userId }; const song = await dispatch(pos ...

Tips for ensuring an element stays anchored at the bottom even when the keyboard is displayed

I recently encountered a situation on one of my pages where an element positioned at the bottom using absolute positioning was causing issues when the keyboard was opened, as it would move to the middle of the page unexpectedly. While this may seem like a ...

Printing a modified div element that was created using jQuery on an ASP.NET MVC webpage after the initial page has finished loading

In my view, there is a div that holds multiple tables generated based on the model. Each row in these tables contains fields that can be edited using TextBoxFor. Through jQuery, rows can be moved between tables and new tables can be created dynamically wit ...

Guide on integrating a plain Service/Provider into nest.js

I recently created a basic TypeScript class in nest.js called JwtTokenService.js. // JwtTokenService.js import { Injectable, Optional } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { JwtPayload } from ' ...

What is the speed difference between calling functions from require's cache in Node.js and functions in the global scope?

Let's imagine a scenario where we have two files: external.js and main.js. // external.js //create a print function that is accessible globally module.exports.print = function(text) { console.log(text) } Now let's take a look at main.js: ...

What is the method for obtaining a dynamic image URL for the <a href> link?

Here is the default Wordpress generated code for displaying images: <div class="image-section"> <a href="http://websitename.com/wp-content/uploads/2019/06/image-1.jpg" target="_blank" rel="noopener noreferrer"> <img src="http://websit ...

Several dropdown menus within the same container, working independently of each other

I recently encountered an issue with a drop-down navigation bar. When I have multiple drop-downs and click on one, it opens as expected. However, if I then proceed to click on another drop-down while the first one is already open, both of them remain open ...

Using Modal Functions in AngularJS Controller

I have been working on a project that utilizes the ui.bootstrap. As per the instructions from the tutorial I followed, my setup looks something like this: 'use strict'; angular.module('academiaUnitateApp') .controller('EntryCtr ...

Tips for adding an array to an array of objects with AngularJs

I'm facing an issue with the array structure in my code. Here's what I currently have: $scope.arrayList=[{FirstName:"",LastName:""}]; $scope.Address=[{address:"",PhoneNumber:""}]; What I want to achieve is to push the $scope.Address array into ...

Unpacking JSON Objects in Typescript: Working with Private Variables

I have a TypeScript model object called user export class User { constructor( private _name: string, private _email: string ) {} public get name():string { return this._name; } public set name(value:string) { this._name = value; } g ...

What is the best way to execute a function in JavaScript and have it return the output as an image

I have created a special function that selects the image source based on a given criterion: function facilityImg(arr, x) { switch (arr[x]) { case 'Yes': return "Images/checked.png"; case 'No': ...

Json node tabbing

[ { "idn" : "liquido", "categoria": "Aromatizante Ambiental Liquido", "productos": [ { "nombre": "Canela" }, { "nombre": "Chanel" }, { "nombre": "Citrus" }, ...

What do you notice about interactions involving 'input type=text' in HTML and JavaScript?

When a new binding is created for the value property on an input, any manual modifications by the user no longer update the value. What happens when the binding is altered? Does regular user interaction involve key press listeners? I've modified the ...

Troubleshooting the issue of jQuery Ajax failing to deliver a PDF

I have been attempting to use jquery, ajax, and django to download a pdf file. Here is my code from the views.py file in Django: if request.POST.get('action') == 'download_labels': order_list = json.loads(request.POST. ...

Contrast between using "export { something }" and "export something" in JavaScript modules

Can you explain the difference between the following code snippets: import something from "../something"; export { something }; vs import something from "../something"; export something; I noticed in the react-is package from react, there is an export ...

Performing a search within a JSON data column in MySQL

I'm currently facing a challenge with my MySQL database column that stores JSON array encoded strings. My goal is to search within the JSON array for values where the "Elapsed" is greater than a specific number and then retrieve the corresponding Task ...

Changing HTML elements dynamically within an ng-repeat using AngularJS directives

I have devised an angular directive where I execute an ng-repeat. The fundamental purpose of this directive is to interchange itself with a distinct directive that depends on a value forwarded into the original directive: <content-type-directive type=" ...

Passing arguments to an external function in jQuery from a dynamically loaded Ajax page

Despite its confusing title, the issue at hand is actually quite simple. My homepage contains a script that loads an external PHP file for a specific section of my website. Within this PHP file, I need to call a function from the main JavaScript file (th ...

Sending JSON data results

I received this JSON response: {"data":[{"series":{"id":"15404","series_code":"TOS","publisher_id":"280","series_short_name":"Tales of Suspense","start_year":"1959","end_year":"1968","published":"1959-1968","type_id":"1","no_issues":"99","published_ ...

Tips for fetching data from a database using AJAX when the values of two drop-down lists are involved

I have successfully implemented an Example where I retrieve data using a single drop-down list from a database. Now, I want to extend this functionality to work with two drop-down lists, where the values retrieved from the database are dependent on the sel ...