jeudi 20 juillet 2023

Why are my divs overlapping with each other (Javascript)

As you very well know by now, I am trying to assign random positions, as in, randomised from a list, to divs. I am achieving so with this code:

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")
}   
    
}

Everything works fine apart from one thing: Because its random, its random. This means that it sometimes or usually chooses the same thing from the list twice or more, resulting in two or more divs having the same position, meaning they overlap each other.

There should be four divs here, but the fourth one has overlapped with the third one, for reasons I have already explained.

I have tried using list.splice to remove ones that have already been chosen, but that didn't work - some divs were resultantly not given a position. I am not sure how to resolve this so that it doesnt choose the same thing, e.g. 100 from the list twice. Help would be appreciated




Aucun commentaire:

Enregistrer un commentaire