These functions will create divs, and A, B, and C will have different left positions (as in the arrays) and different classes with different dimensions. Another function will call them in a set interval and will decrease all the "--bottom" with time at the same speed (they will move down ). I have a feeling that these functions can be simplified to one, but I am new to javascript.
function getCustomProperty(elem,prop){
return parseFloat(getComputedStyle(elem).getPropertyValue(prop)) || 0
}
function setCustomProperty(elem,prop,value){
elem.style.setProperty(prop, value)
}
function incrementCustomProperty(elem,prop,inc){
setCustomProperty(elem,prop, getCustomProperty(elem,prop) inc)
}
const worldElem = document.querySelector("[data-world]")
function createA() {
let posits = [15,45,75]
let posit = posits[Math.floor(Math.random()*posits.length)]
const A = document.createElement("div")
A.dataset.A = true
A.classList.add("A")
worldElem.append(A)
setCustomProperty(A, "--bottom", 100)
setCustomProperty(A, "--left", posit)
}
function createB() {
let posits = [11.5,23.5,41.5,53.5,71.5,83.5]
let posit = posits[Math.floor(Math.random()*posits.length)]
const B = document.createElement("div")
B.dataset.B = true
B.classList.add("B")
worldElem.append(B)
setCustomProperty(B, "--bottom", 100)
setCustomProperty(B, "--left", posit)
}
function createC() {
let posits = [14,23.5,44,53.5,74,83.5]
let posit = posits[Math.floor(Math.random()*posits.length)]
const C = document.createElement("div")
C.dataset.C = true
C.classList.add("C")
worldElem.append(C)
setCustomProperty(C, "--bottom", 100)
setCustomProperty(C, "--left", posit)
}
CodePudding user response:
There seem to be two varying values when comparing your three functions A, B, and C:
- the id ("A", "B" or "C")
- the
posits
array
So, you could pass that information as an argument to the function. Either as two separate arguments, or one object that combines that information.
For example:
function create(config) {
let [[id, posits]] = Object.entries(config);
let posit = posits[Math.floor(Math.random()*posits.length)];
const div = document.createElement("div");
div.dataset[id] = true;
div.classList.add(id);
worldElem.append(div);
setCustomProperty(div, "--bottom", 100);
setCustomProperty(div, "--left", posit);
}
var A = [15,45,75];
var B = [11.5,23.5,41.5,53.5,71.5,83.5];
var C = [14,23.5,44,53.5,74,83.5];
// Example calls:
create({A});
create({B});
create({C});