Change the position of an array element when displayed on an HTML page

I'm trying to figure out a way to manipulate the position of an HTML element that is stored inside an array. The issue I am facing is that my code generates a new div every time a specific function is called, and this div has a class applied to it for animation purposes.

After the animated div falls down the screen, I need to randomly adjust its X position by a certain number of pixels. Below is the code snippet I have been working on:

for (i = 0; i < 1; i++) {
   setInterval(function newRock(item){
     let num = Math.floor(Math.random() * 1000);
     let num2 = Math.floor(Math.random() * 1500);
     const rocks = document.querySelector(".rocks");
     const rock = document.createElement("DIV");
     rocks.appendChild(rock)
     rock.classList.add("rock0");
     rock.classList.add("animate");
     rock.style.left = `${num}px`;
     rock.style.top = `${num2}px`;
     rockArray.push(rock.className);
   classNumber++;
 },10000);
}


setInterval(() => {
 console.log(rockArray)}, 10000)
});

rockArray.forEach((item) => {
 item.style.left = `${num}px`;
});

setInterval(function() {
 let num = Math.floor(Math.random() * 1000);
 let num2 = Math.floor(Math.random() * 1000);

 document.querySelector(".rock0").style.left =  `${num}px`;
 document.querySelector(".rock1").style.left =  `${num2}px`;
}, 3000);

Answer №1

If your position property is set to static, relative, or absolute, the left or right CSS properties will have no effect.

Answer №2

To make use of the left and right properties, your HTML element must be positioned. Positioned elements are those with the position attribute set to one of the following values: fixed, absolute, relative, or sticky.

  • When the position is set to absolute or fixed, the left (right) property specifies the distance between the element's left (right) edge and the left (right) edge of its container block. The container block refers to the ancestor element that the element is relatively positioned to.
  • For a position set to relative, the left (right) property indicates how far the element's left (right) edge has been shifted from its original position.
  • When using sticky for positioning, the left (right) property is crucial in determining the sticky-constraint rectangle.
  • If the position is static, then the left (right) property will have no impact.

Refer to the following articles:

https://developer.mozilla.org/en-US/docs/Web/CSS/left https://developer.mozilla.org/en-US/docs/Web/CSS/right

Update:

In the given code snippet, the variable num appears undefined.

rockArray.forEach((item) => {
 item.style.left = `${num}px`;
});

What does the value of num represent in ${num}px? It seems to be undefined.

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 there a way to add a delay when opening all of the links on my web page

Has anyone experimented with implementing time delays on global links before? I am aiming to have all my links open with a delay in order to create a smoother transition between pages for an artistic touch. However, I seem to be encountering some issues ma ...

The if-else condition is creating issues with the functionality of the buttons

Update #1 - Enhanced query, fresh functional link. Live site: The challenge at hand revolves around an if-else statement related to the form buttons on the right-hand column of the webpage. Scroll past the header and navigation to witness the issue in ...

Vue: Simple ways to retrieve state data in MutationAction

I'm having trouble accessing the state inside @MutationAction Here is the setup I am using: Nuxt.js v2.13.3 "vuex-module-decorators": "^0.17.0" import { Module, VuexModule, MutationAction } from 'vuex-module-decorators' ...

How to return a variable to Express when clicking a button?

Imagine having a list of 10 elements, each with a unique id as their name, and the user has the ability to add more items to the list at any time. If I were to click on an element, my goal is to have Express retrieve the id of that specific element. If it ...

Issues with jQuery not detecting click events

Here is an example of HTML: <div class="sortable-buttons"> <ul> <li><a>Recent</a></li> <li><a>Popular</a></li> <li><a>Being Discussed</a></li> </ul> </div ...

The innovative technique of using pure CSS to secure the bottom edge of a div to the viewport

Is there a way to keep two container divs positioned x pixels from the bottom of the viewport without using position absolute|fixed? I want them to remain as position: relative for proper DOM flow. Searching for a CSS-only solution that works in IE7+. Mos ...

Disable Jquery toolstrip while the menu is open

Currently, I am utilizing the jQuery toolstrip plugin in my project. I have a requirement to disable it whenever the sidebar menu is opened. Below are the HTML codes for my menu with li tags: <div class="sidebar-wrapper" id="sidebar-wrapper"> <ul ...

Implementing selective image loading with HTML and angularJS

This image reveals the issue at hand Within this HTML code snippet, some of my images are displaying on the webpage while others are not. How can I go about resolving this? <img src="img/uploadFiles/{{room.imageLocation.split('//')[6]}}/{{ro ...

Error sound produced when detecting KeyCode on the keyboard

I'm currently working on a JavaScript project that involves capturing keyboard input. However, I'm encountering an issue where every time the user presses a key, it triggers an error sound. Is there a way to disable this sound? ...

Guide to automatically loading a default child route in Angular 1.5 using ui-router

Hello, I am looking to set a default child route to load as soon as the page loads. Below is the code snippet: $stateProvider.state('userlist', { url: '/users', component: 'users', data:{"name":"abhi"}, resolv ...

providing the context for the hover title description

I seem to be struggling with a seemingly simple issue and can't find a solution. Below is the code I have written: <html> <head> <style> span.dropt { border-bottom: thin dotted; background:white; } </style> </head> ...

The concept of CSS inheritance within div elements

I've been researching extensively about the concept of CSS inheritance, but I have come across a puzzling question that remains unanswered. Consider the code snippet below: <!DOCTYPE HTML> <html> <head> <style type="text/css"> ...

AddThis plugin in Wordpress is unresponsive when used with a theme that relies heavily

I've been struggling to properly set up the AddThis Wordpress plugin to display share buttons below each post in an AJAX theme. After inserting this code into the custom button field on the settings page: <div class="addthis_toolbox addthis_defa ...

Issue occurs when using Angular Firebase $createUser method

I'm stuck on this issue. I'm attempting to set up a user with AngularFire using $firebaseAuth instead of the deprecated FirebaseSimpleLogin, as advised in the documentation. I am confident that the form is submitting a valid email and password, b ...

Converting HTML tables into arrays

I have JSON content that needs to be transformed into an array, specifically from a HTML table with cell values. Those cells should be combined into a single array for further use in the project. Struggling with the conversion of cell values into an arra ...

The media query was running smoothly until it unexpectedly stopped functioning

I've encountered an issue where something that used to work perfectly fine suddenly stopped working :( @media only screen and (max-width: 768px) { form, button, input { width: 80vw !important; } } <meta name="viewport" content="width=de ...

Remove a data entry from the MySQL database by selecting the corresponding row in the table and utilizing the DELETE function

Is there a way to remove a record from my MySQL database by clicking on a row in a table that is generated using ejs? Below is the code I am currently using to generate the table rows. <% res.forEach(function(item){ %> <tr> ...

Using an Ajax Post Call to send FormData leads to a Get request instead

Having trouble with sending a simple form via POST method. I load the form content using AJAX: $(function() { var arg = { "operation": "upload", "step": "0" ...

Issue with PrimeNG Carousel width on mobile devices

Currently, I am in the process of developing a system interface with Angular and PrimeNG specifically for mobile devices. The main requirement is to have a carousel to display a set of cards. After evaluating different options, I decided to utilize the ngP ...

rendering google charts using jade template

I am facing an issue while trying to display a google annotated chart on my jade project. I managed to successfully load a pie chart, but I am having trouble rendering a chart that requires the container element size to be explicitly defined. You can find ...