What could be causing my divs to collide with each other in a Javascript environment?

As you may be aware, my current task involves assigning random positions from a list to various div elements. The code I am using to achieve this is as follows:

var list = [100,210,320,430];
var square1 = document.getElementById("square1")
var square2 = document.getElementById("square2")
var square3 = document.getElementById("square3")
var square4 = document.getElementById("square4")
var squares = [square1,square2,square3,square4]
for(let looprun = 0; looprun<4; looprun++){    
    r=Math.floor(Math.random()*list.length)                       
    console.log(looprun)
    squares[looprun].style.left = (list[r])+"px";
    list.splice(r)
    if(looprun === 3){
    console.log("End of Loop Reached")
}   
    
}

While everything is functioning correctly, there is one issue that needs addressing: due to the random nature of the selection process, there are instances where div elements end up with the same position, resulting in overlap.

For instance, in the image below, you can see that the fourth div has overlapped with the third, as described above.

Attempts to prevent duplicate selections using list.splice have not been successful, as some div elements remain unpositioned. I am seeking assistance in resolving this issue to ensure that the same value from the list is not chosen multiple times. Any guidance would be greatly appreciated.

Answer №1

I attempted to utilize list.splice in order to eliminate those that have already been chosen, but unfortunately, it was ineffective - resulting in some divs not being assigned a position.

This issue arises from the following section of your code:

for(let looprun = 0; looprun<4; looprun++){    
    r=Math.floor(Math.random()*4)

The problem lies in hardcoding the value 4 instead of utilizing the array's actual length.

As you diminish the size of list, employing Math.random()*4 may exceed the array's boundaries at times.

It is advisable to use Math.random()*list.length instead.


list.splice(r)

If you exclude the second parameter of splice, which specifies the *number of items to remove, it will delete from r to the end of the array.

What you actually need is to remove only one item (the one you are assigning to the div) from the array.

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 React modal refuses to disappear, stubbornly clinging to the original component it sprang from

Hey there, I'm a beginner in learning React and I'm encountering an issue with my popup modal component. Even after showing the modal, I can still interact with and click on the main UI elements. Can anyone assist me with this problem? https://i ...

Populate User Interface Popover - Placement on Compact Display

I have been grappling with finding a solution to position the material ui popover beneath my anchor consistently, even on smaller screens. Take a look at this sandbox example. The current setup is working alright, but the issue is that the scroll is cont ...

What is preventing me from applying JSON patches in both directions?

My current project involves merging JSON objects using patches following the guidelines outlined in RFC 7396. To achieve this, I am utilizing JSON Merge Patch along with Pretty JSON. Below is the code snippet I have: #!/usr/bin/env node var jsonmergepatch ...

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...

What is the correct way to set up the Suspense position within a Canvas?

Looking to adjust the position of a 3D model within a Canvas based on the x, y, and z axes? <div> <Canvas shadows dpr={[1, 2]} camera={{position: [5, 50, 5], fov: 10}}> <Suspense fallback={null}> <Model/> < ...

The JS Uri request is being mishandled

My current challenge involves POSTing to a server using Request JS, specifically with some difficulties related to the path. return await request.get({ method: 'POST', uri: `${domain}/info/test/`, body: bodyAsString, head ...

Moving a mouse from one element to another does not reset its state

Link to code: https://codesandbox.io/s/objective-darwin-w0i5pk?file=/src/App.js Description: There are four gray squares in this example, each with a different shade of gray. The goal is to change the background color of each square when the user hovers o ...

Unable to get the Express.js Router functioning correctly on my server, even in a basic scenario

I am encountering an issue with using express.Router(). It was not functioning correctly in my application for serving JSON from MongoDB, so I attempted to simplify the scenario. However, I am receiving a 404 Not Found error in the request. What steps shou ...

Click the button to access the provided link

I need to add a link for redirection to some buttons. Here is an example of the button code: <Tooltip title="Open New Ticket"> <IconButton aria-label="filter list"> <AddTwoToneIcon /> </IconButton> </T ...

increase the number of rows in the table automatically

I've encountered an issue while working on a form that involves getting a value from a jQuery spinner and dynamically adding that number of rows to a table inside the form. Despite using firebug to debug, I couldn't pinpoint the exact cause of th ...

I'm experiencing an issue where the video from my server is not being displayed within the <video> tag in the browser, but when using the web URL, the video plays

When it comes to uploading a video, there are two options available: 1) Provide the web URL for the video, 2) Upload the actual video file. The <video> tag works smoothly with a web URL as the source, but issues may arise when trying to play an uplo ...

The impact of React-router's history within the connect function of the react-redux provider

After successfully connecting my presentational-functional component to the redux store using the connect function, I encountered an issue regarding redirection upon triggering the getTask action or when apiGetTask has completed. I attempted to implement t ...

What are the steps for defining the maximum and minimum values in AngularJS?

I'm working with the following HTML markup: <div class="input-group-icon">Max <span class="error">*</span> <div class="input-group"> <input style="border-right:none;" name="available_funds_max" ng-model="attributes.avai ...

Creating a persistent footer in a modal: A step-by-step guide

I'm currently working on a react-modal that slides in from the bottom of the screen with an animated effect. The challenge I am facing is getting the footer of the modal to stay fixed at the bottom of the browser window. Despite using the standard CSS ...

Header text refuses to cooperate and center itself

Struggling to find the best way to center the "Header" text while keeping the icon in place. I've tried using text-align: center;, but it's not producing the desired results. Could anyone provide guidance on how to achieve this? Thanks. IMG: ...

Retrieving the initial element that satisfies a condition within Angular

Here is the Angular 1.0 code that I am currently struggling with: <div ng-repeat="ebook in vml.ebooks"> <img data-ng-src="{{ ebook.files.filter(function (v) { return v.type === 'ebook.cover'; })[0].url }}" /> </div> Un ...

Java and Selenium: Struggling to Find Element based on Attribute

Attempting to click a button on a webpage with the given HTML code: <html lang="en" webdriver="true"> <head> <body class="scbody" style="background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAKCAYAAAB10jRKAAAAGXRFWHRTb2 ...

Tips for incorporating animation when opening a Jquery SimpleModal

The SimpleModal website features an animation-enabled example with the following sequence: 1. Display modal only 2. Fade in the overlay The code snippet for this animation is as follows: $("#the-div").modal({ onOpen: function (dialog) { dialog.overl ...

Update image attributes (such as src, alt, etc.) after a successful AJAX request (and also help me troubleshoot my AJAX

The image link I am currently using is: echo "<br/><div class='right' id='post" . $id . "'> <img id='thumb' src='/images/like.png' title='Like it?' alt='Like button' onC ...

Using an AWS API Gateway, an HTTP client sends a request to access resources

I have a frontend application built with Angular and TypeScript where I need to make an HTTP request to an AWS API Gateway. The challenge is converting the existing JavaScript code into TypeScript and successfully sending the HTTP request. The AWS API gat ...