Tips on applying array values as styles to a div element

I have a list of numbers stored in an array and an equal number of div elements. I need to assign each value from the array to a corresponding div.

var xList = [265, 152, 364]
var yList = [125, 452, 215]

All div elements have the same class name.

function createContent(e) {
    var divMark = document.createElement("div");
    divMark.classList = `markers mark`;
    var img = $('<img class="comment" src="indeksiraj-1.png" alt="myimage" />');
    $(divMark).append(img);
}

The goal is to assign the first value to the first div, the second value to the second div, and so on.

I've considered using CSS in the following way.

$(".markers").css({ top: yList + "px", left: xList + "px" });

Answer №1

Initially, it seems like you are blending raw JavaScript with JQuery. Given the current trends, it is advisable to steer clear of JQuery as raw JS methods are equally straightforward, but notably faster. Moreover, they have been functioning well for the past 4 years across all browsers supported by their respective developers. To address this, I have replaced all JQuery components in your query with raw JS components in my response.

Simple Solution

Essentially, the correct approach to achieve your requirement is to execute it within your function. For instance:

function createContent(xPos, yPos) {
    var divMark = document.createElement('div');
    divMark.classList = 'markers mark';
    divMark.style.top = yPos + 'px';
    divMark.style.left = xPos + 'px';

    var img = document.createElement('img');
    img.classList = 'comment';
    img.src = 'indeksiraj-1.png';
    img.alt = 'myimage';

    divMark.appendChild(img);
}

Subsequently, you will have to iterate over the arrays to invoke the function.

for (var i = 0; i < xList.length && i < yList.length; i++) {
    createContent(xList[i], yList[i]);
}

Additional Consideration

As an alternative, you could utilize a single array for the xList and yList, enabling a more legible loop implementation.

var posList = [
    {x: 265, y: 125},
    {x: 152, y: 452},
    {x: 364, y: 215},
];

posList.forEach(({x, y}) => {
    createContent(x, y);
});

Preserving the Function Signature

After reviewing the additional context provided by your fiddle, it is apparent that the createContent function is triggered by a button click and encompasses more functionalities beyond what you shared. I have solely focused on removing the JQuery component from your snippet and inserted a placeholder for you to incorporate the remaining functionality in the createContent function.

function createContent(e) {
    var divMark = document.createElement('div');
    divMark.classList = 'markers mark';

    var img = document.createElement('img');
    img.classList = 'comment';
    img.src = 'indeksiraj-1.png';
    img.alt = 'myimage';

    divMark.appendChild(img);

    // ...insert the remaining code in the function here

    return divMark;
}

for (var i = 0; i < xList.length && i < yList.length; i++) {
    var mark = createContent();

    mark.style.top = yList[i] + 'px';
    mark.style.left = xList[i] + 'px';
}

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

Looking to add elements to a specific div dynamically using jQuery? Let's explore how to insert comments seamlessly

I would like to implement a comment system that adds entered comments to a specific div. Here's the code I have so far: <ul class="comments"> <li> <a class="commenter_name" href="/">Dushyanth Lion</a> ...

Maximizing Server Performance with Query Data Caching

I am currently developing an Express app that involves transferring data from views to a database. However, the majority of the data needs to be linked to other data within different tables in the database. For instance, there is a "choose student name" d ...

How can I modify the dot colors on a graph using chart.js?

Need assistance with changing the color of graph data points https://i.sstatic.net/QGJBv.png Here is my JavaScript code snippet I have successfully created a graph using chart.js. However, I now want to differentiate data points by displaying different c ...

Error: Attempting to insert or update the "tokens" table violates the foreign key constraint "tokens_userId_fkey" in Sequelize

I am facing an issue that I can't seem to resolve, as I keep encountering an error related to a constraint violation. The tables involved in this problem are Token and User, which are linked through the userId column. The error occurs when I try to cr ...

My Jquery CSS Checkbox is failing to register when it's checked

I have implemented custom checkboxes using a custom CSS checkbox generator. $( ".button" ).click(function() { if(document.getElementById('terms_checkbox').checked) { alert('Checkbox is checked'); } else { alert('Chec ...

Conditionally display content based on the existence of a specific value within an array

Is there a way in AngularJS to display a value using ng-show, such as ng-show = "role in ['admin', 'user', 'buyer']" I want to display a div if the role matches any of the elements in the array. ...

Is specificity a characteristic of JavaScript?

After setting a div in my HTML file to have a height of 100px and a width of 100px, I attempted to retrieve the height using JavaScript. This is what I tried: console.log(document.GetElementById("box").style.height); // The div had an ID of "box" and w ...

Can display-inline-block support top margin and text alignment?

Can you please explain if the top margin and text-align properties work for both display: inline and display:inline-block? If they do, could you provide some insight as to why? ...

Searching for a contiguous subarray with a specific sum in linear time complexity (O(n))

After solving the question, I realized that the time complexity of my code is O(n^2). The code includes two loops, leading to the O(n^2) time complexity. Is there a way I can modify my code to achieve the same solution in O(n) time instead? import java. ...

Switching over the database for a session away from using ajax

I am currently working with an XML API that interacts with a database. My website utilizes the functions of this XML API to retrieve data from the database. I am facing a challenge where I need to update the database based on the user's selection on t ...

Tips for retrieving the output from an Azure Function

Just getting started with Azure Functions and I have this code snippet: module.exports = function (context, req) { context.log('JavaScript HTTP trigger function processed a request.'); context.log(context.req.body.videoId) ...

Tips for rearranging sibling divs while maintaining the order of their child elements

Is there a way to shuffle the order of div classes shuffledv, while maintaining the same order of id's each time the page is refreshed? <div class="shuffledv"> <div id="2"></div> <div id="3"></div> <div id="1">< ...

Adjusting the color of an HTML slider button as it moves

In my setup, I have a straightforward slider that I plan to use for controlling the movement of a stepper motor based on the slider's position. I wanted to give the website where this will be hosted a professional look, so I've spent quite some t ...

Tips for updating and transferring a variable within a callback function

I have implemented a function using the SoundCloud API that retrieves a song URL, obtains the associated sound ID from the API, and then passes that ID to a callback for streaming purposes and updating the page. The data is successfully retrieved from the ...

obtain data in JSON format from a Node.js server and display it on an HTML

I am currently working on a feature that involves sending an AJAX request to the server and receiving the output of a MySQL query on the page http://localhost:3000/result.html upon clicking a button. <body> <form action="/setLocation" method=" ...

While building with Next.js, a ReferenceError may occur if the sessionStorage is not defined

While using Next.js 13 App router, I encountered an issue with storing the JWT token received upon login in session storage. It all worked smoothly when accessing the token in my page.js pages across different routes as long as the page was a client compon ...

recording the results of a Node.js program in PHP using exec

I'm attempting to retrieve the output from my node.js script using PHP exec wrapped within an ajax call. I am able to make the call and receive some feedback, but I can't seem to capture the console.log output in the variable. This is how I exec ...

CSS problem with rotating image carousel

I'm currently working on incorporating the moving box feature displayed at the bottom of this page. Despite following the CSS code provided, I am facing an issue where the left navigation arrow is not appearing. Can anyone provide any insights or sugg ...

Steps to remove a specific child element using jQuery:

CSS: <h1><br style="clear:both;"></h1> I am currently working on a project that involves using the Wikipedia API. One issue I've run into is cleaning up the raw HTML output from Wikipedia, specifically dealing with removing a speci ...

When utilizing div.load, jQuery and other JavaScript sources may not be defined

When you load a page using jQuery load: $("#myDiv").load("page.php",{foo: bar}); The head section is included in the index: <head> <script src="/assets/plugins/jQuery/jQuery-2.1.4.min.js"></script> <script src="/assets/plugi ...