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

"Troubleshooting: Why isn't my jQuery AJAX POST request successfully sending data to

Here is the jQuery code snippet that I am currently working with: $("#dropbin").droppable( { accept: '#dragme', hoverClass: "drag-enter", drop: function(event) { var noteid = "<?=isset($_POST['noteid']) ? ...

Ways to keep selected values in the Select box without unchecking them again?

Hello there, I am relatively new to ReactJS and currently facing an issue with Selects. Specifically, I have a Select component that displays a list of names using MenuItem. My goal is to have certain names pre-selected in the Select dropdown upon initial ...

What is the method to prolong the end date of fullCalendar.js through Javascript?

I am facing the same issue as this individual. I am unsure of how to add one day to the end date. I do not want to alter the database value, only modify it on the HTML page. Currently, this is my calendar (no Moment.js joke intended): $(document).ready(f ...

What is the best way to transform an array of arrays into an array of objects using AngularJS?

Here is some code I am working on: $scope.students=[]; $scope.students[[object Object][object Object]] [0]{"id":"101","name":"one","marks":"67"} [1]{"id":"102","name":"two","marks":"89"} I would like to reformat it into the ...

Ensuring the script waits for the complete loading of iframe prior to

I'm faced with an issue on the website I'm currently working on. There's a Live Chat plugin integrated on an iframe, and I need to change an image if no agents are available. Interestingly, my code works perfectly fine when tested on the con ...

My Jquery "animate" is only triggered once instead of on each function call. What could be causing this issue?

I have set my navigation to dock at a specific document height on the top of the viewport, and when it docks, it should display a dropdown animation. $(document).scroll(function(){ var x = $(window).scrollTop(); if(x>=700){ $("header ...

What steps can be taken to stop the update function from inserting data into MongoDB from a Meteor application

Within my Meteor method, I have implemented a function to check for existing documents. If the document is not found, it gets inserted into the database. However, if it is found during a second attempt, the document is updated and a new one is also inserte ...

Make an AJAX GET call to an ASP.NET Web API endpoint

Here is the ajax script I am using: $.ajax({ dataType: 'json', url: url, data: tuDispId, type: "GET", success: function (data) { bindData(data); $("#ale ...

Creating an extra dialogue box when a button is clicked in React

Having an issue with displaying a loading screen pop-up. I have an imported component named LoadingDialog that should render when the state property "loading" is true. When a user clicks a button on the current component, it triggers an API call that chang ...

Code functions properly on local host but encounters errors when deployed to live server

My comment system was working fine on localhost using PHP, AJAX and JavaScript. However, after transferring my website to a live server, the code does not seem to be functioning properly. Here is an example of the script: <script type="text/javascript ...

Using Javascript Reduce to Manipulate Objects

Here is the data I am working with: let info = [ {id: 1, name: "John Doe", type: "A", amount: 100}, {id: 2, name: "Jane Smith", type: "B", amount: 150}, {id: 3, name: "Alice Johnson" ...

Access to create permissions for collection "faunaDB" denied due to authorization privileges in FQL query using User Defined

I have a custom user role for security that has a predicate function for creating entries in a collection named formEntryData. When I try to create an entry without the function, it works fine. However, when I use the provided function below, I receive a p ...

Page jumping vertically in Chrome upon reload, with Firefox and Internet Explorer functioning properly

Utilizing this jQuery script, I am able to center a website vertically within the browser window if it exceeds the height of the outer wrapper-div, which has fixed dimensions. $( document ).ready(function() { centerPage(); )}; // center page vertic ...

Tips on updating the arrow icon after clicking on a dropdown menu

HTML: <div class="customSelectContainer"> <ul> <li class="initial">Choose</li> <li data-value="value 1">Option 1</li> <li data-value="value 2">Option 2& ...

(Processing) Eliminating Previously Utilized Element from Array

Apologies for the poorly worded title. I'm working on a "War" game in Processing for my Programming course. I need help modifying my code to remove each used card from the deck/array. I've come across some references to "ArrayList" in online post ...

Using AJAX to showcase data from a table in a database using the <select> tag but with an unfinished submit process

I am encountering an issue with my code. When I submit the value in getinv.php, it only returns a partial value. For example, when I click '2016-08-27', it only retrieves '2016'... My question is, how can I ensure that the exact value ...

Preventing an infinite re-render loop caused by event listeners in React

One functional component is causing me some trouble: export default function Nav({photo}) { const [isOpen, setIsOpen] = useState(false) const [width, setWidth] = useState(window.innerWidth); const breakpoint = 768; useEffect(() => { ...

Troubleshooting issue with rendering <li></> using array.map: Map's return statement is producing undefined output

Trying to implement pagination in a React project and facing issues with rendering a set of li elements within an ul. The renderPageNumbers function is returning undefined in the console, even though I can see the array being passed and logging out each el ...

Having trouble retrieving the data from the angular app factory

I'm attempting to pass a variable between controllers using Angular's Factory. Here is the code snippet I have for this: var app = angular.module('chartApp', ['ngRoute']); app.factory('UserVerified', function() { ...

What is the best way to focus the video on its center while simultaneously cropping the edges to keep it in its original position and size?

I'm trying to create a special design element: a muted video that zooms in when the mouse hovers over it, but remains the same size as it is clipped at the edges. It would be even more impressive if the video could zoom in towards the point where the ...