Search code examples
javascriptfunctiondom-events

How to add new box with size of the last box


I have a problem with adding a function which will create an amount of boxes with rising size and when i try to add more I will start from the size of the previous last box.

So far i have a code like this:

function getRandomHexColor() {
    return `#${Math.floor(Math.random() * 16777215).toString(16)}`;
}
const input = document.querySelector("#controls>input");
const createBtn = document.querySelector("button[data-create]");
const destroyBtn = document.querySelector("button[data-destroy]");
const boxCollection = document.querySelector("#boxes");

const createBoxes = (amount) => {
    amount = input.value;
    for (let i = 0; i < amount; i += 1) {
        let newBox = document.createElement("div");
        newBox.style.height = `${30 + 10 * i}px`;
        newBox.style.width = `${30 + 10 * i}px`;
        newBox.style.background = getRandomHexColor();
        boxCollection.insertAdjacentElement("beforeend", newBox);
    }
};

createBtn.addEventListener("click", createBoxes);

const destroyBoxes = () => {
    boxCollection.innerHTML = "";
};

destroyBtn.addEventListener("click", destroyBoxes);

I was thinking about adding a new var which will be the lastChild of const boxCollection and add it to height and width of newBox. Am I thinking right?


Solution

  • You can either create a variable with the current number of boxes or you can just count the current number each time you add more. In the example the current number (currentCount) is based on the length of a querySelectorAll().

    function getRandomHexColor() {
      return `#${Math.floor(Math.random() * 16777215).toString(16)}`;
    }
    
    const boxCollection = document.querySelector("#boxes");
    
    const createBoxes = e => {
      e.preventDefault();
      let amount = parseInt(e.target.amount.value);
      let currentCount = boxCollection.querySelectorAll('div').length;
      Object.keys([...Array(amount)]).forEach(i => {
        let incVal = parseInt(i) + currentCount;
        let newBox = document.createElement("div");
        newBox.style.height = `${30 + 10 * incVal}px`;
        newBox.style.width = `${30 + 10 * incVal}px`;
        newBox.style.background = getRandomHexColor();
        boxCollection.insertAdjacentElement("beforeend", newBox);
      });
    };
    
    const destroyBoxes = e => {
      e.preventDefault();
      boxCollection.innerHTML = "";
    };
    
    document.forms.create.addEventListener("submit", createBoxes);
    document.forms.destroy.addEventListener("submit", destroyBoxes);
    <form name="create">
      <input type="number" name="amount" />
      <button>Create</button>
    </form>
    <form name="destroy">
      <button>Destroy</button>
    </form>
    <div id="boxes"></div>