I made a gradient sandbox program with JS/HTML/CSS, basically to practice dom manipulation. So far, I have a working program where I can move a box around the screen with the arrow keys, change it’s heighth, width, border radius, and colors. I would like to be able for the program to create a new box and then pass the ID attribute of the old box to the new box, so the user will be able to do the same manipulations with the new box, while the old box sits on the screen with the user changes in place. So far, trying to pass the id to the new box has just made the program crash.
This code activates on "n". it does create a new box, but the new box can not be manipulated, and the old box does not retain it’s changes, and the background color of the program messes up:
function newBox(event) {
box.style.border = "none";
box.id = ""
let box2 = document.createElement("div");
body.appendChild(box2);
box2.id = "box";
}
The beginning of the program contains the line:
let box = document.getElementById('box')
and the box
variable is what gets manipulated by keydown events.
I also tried assigning a global counter variable i
and changed the above line to:
let box = document.getElementById('box' + i.toString() )
the newBox()
function would increment the counter and assign the new box an id of ('box' + i.toString())
. This also caused the program to crash.
Thanks for looking at the problem. I’m very new to coding, so I’ll take "What you’re trying to do is completely impossible" as a perfectly acceptable answer.
2
Answers
Instead of using an "ID" use "Class". Also, you could use JS to create an "Object / Template" of your "Box" element to help differentiate between new instances of your box element. Create a "Method" for your box "Object" where it removes the event listener when creating a new instance. You could store these Object instances in an "Array" for easier "Indexing".
Hopefully that isn’t confusing. I tried to give you keywords that I believe would help get you in the right direction.
MDN – Remove Event Listener
I assume your event listeners are all bound to the
box
element and won’t be registered onbox2
after you have added it. To manipulate your box you don’t actually need the ID, you just need to store the reference to the last box you created.In my example I still set the ID, as that was part of your question. Whenever "n" is typed on the keyboard, a possible old box will have its ID set to blank (you might want to remove the ID altogether, using removeAttribute()), a new element will be created with the given "#box" ID, which will then be movable via cursor.