JSFiddle - React, Tailwind, and code Playground
by zxzc0
HTML
<main>
<div id="fh-form">
<div class="row">
<div class="row-cards">
<textarea class="front" placeholder="front"></textarea>
<textarea class="back" placeholder="back"></textarea>
</div>
</div>
</div>
<div id="new-card-bt">Add a new card</div>
</main>
CSS
body {
background-color: #21262D;
color: #fff;
}
#new-card-bt{
cursor: pointer;
}
textarea{
resize: none;
}
JavaScript
function keydownHandler(event) {
if ((event.key === "Tab")) {
addCard();
this.removeEventListener("keydown", keydownHandler); //handler for this TEXTAREA is no longer needed. remove it
event.preventDefault(); //prevent current event from being processed
}
}
function addHandler() {
const lastBack = document.querySelectorAll(".back");
lastBack[lastBack.length - 1].addEventListener("keydown", keydownHandler);
}
let i = 1;
function addCard() {
const div = document.querySelector("#fh-form");
const row = rowTemplate.cloneNode(true); //clone the card template
div.appendChild(row);
addHandler(); //add `keydown` to the last `back` TEXTAREA element
const lastBack = document.querySelectorAll(".front"); //move input focus to the `front` TEXTAREA element of newly created card
lastBack[lastBack.length - 1].focus();
incr.innerHTML = (i++) + ".";
}
const rowTemplate = document.querySelector(".row").cloneNode(true); //clone/copy initial `row` element as card template
addHandler(); //add `keydown` to the last `back` TEXTAREA element
const bt = document.querySelector('#new-card-bt');
bt.addEventListener("click", addCard);