I have javascript script that creates the same div everytime the user clicks enter and then set the event listener to the new input in the new div.
example:
//creates the container, text and input for the new line
function createNewUserInputLine() {
var body = document.body;
var inputLine = document.createElement("div");
var inputLineLabel = document.createElement("p");
var inputLineTextbox = document.createElement("input");
var labelText = document.createTextNode("Click enter to display Hello World");
inputLine.className = "input-line";
inputLineLabel.className = "input-label"
inputLineTextbox.className = "user-input"
inputLineLabel.appendChild(labelText);
inputLine.appendChild(inputLineLabel);
inputLine.appendChild(inputLineTextbox);
body.appendChild(inputLine);
addListenerForUserInput();
}
//adds an event listener for the newest input line to capture when
//the user clicks the enter key, and removes the listener and disables
//the input from the last input line
function addListenerForUserInput() {
var userInputArray = document.getElementsByClassName("user-input");
var activeUserInput = userInputArray[userInputArray.length - 1];
var unactiveUserInput = userInputArray[userInputArray.length - 2];
function captureEnterPress(event) {
if (event.key === "Enter" || event.keyCode === 13) {
event.preventDefault();
createOutputLine();
}
}
if (userInputArray.length > 1) {
unactiveUserInput.removeEventListener("keyup", captureEnterPress);
unactiveUserInput.disabled = true;
}
activeUserInput.focus();
activeUserInput.addEventListener("keyup", captureEnterPress);
}
//creates the output line
function createOutputLine() {
var element = document.body;
var br = document.createElement("br");
var outputLine = document.createElement("p");
var outputLineText = document.createTextNode("Hello World!");
outputLine.className = "output-line";
outputLine.appendChild(outputLineText);
element.appendChild(outputLine);
element.appendChild(br);
createNewUserInputLine();
}
//when the page is finished loading it prints the first line
onload = () => {
createNewUserInputLine();
}
The html file is empty and the first div is created in the onload method. Is this the right way to do it, or should I create the first div in the html and then attach the event listener in the javascript and that will add the new divs each time the user clicks enter?