I'm just a newbie and I'm trying to learn jQuery and JavaScript so I thought to develop a memory card for learning languages project to just get used to it, my code creates a new card and shows it without storing any data and refreshing the browser and it has to, right now I completed the delele functionality though toggling doesn't always work properly, could you help me to figure out why?
Here following is my code:
function reloadData(el) {
$("#content").html("");
for (let i = 0; i < el.length; i++) {
$("#content").append(el[i])
}
var cards = $(".card");
var deleteButtons = $(".delete");
for (let x = 0; x < cards.length; x++) {
deleteButtons[x].addEventListener("click", function() {
var result = [];
for (let p = 0; p < cards.length; p++) {
if (p == x) {
continue;
} else {
result.push(cards[p]);
}
}
reloadData(result);
});
}
}
$("#createCard").click(function() {
var a = $("#txt1").val();
var b = $("#txt2").val();
$("#content").append(
"<div class='card' style='float: left; width: 100%; height: 35px;'><div class='words' style='float: left; width: 70%;'><p style='float: left;' class='original'>" + a + "</p><p style='float: left; display: none;' class='translation'>" + b + "</p></div><div style='float: left; width: 30%;'><a class='toggle'>ruota</a><a class='delete'>elimina</a></div></div>"
);
var cards = $(".card");
var deleteButtons = $(".delete");
var toggle = $(".toggle");
var words = $(".words");
for (let i = 0; i < cards.length; i++) {
toggle[i].addEventListener("click", function() {
var original = words[i].getElementsByClassName("original")[0];
var translation = words[i].getElementsByClassName("translation")[0];
if (original.style.display == "none") {
original.style.display = "block";
translation.style.display = "none";
} else {
translation.style.display = "block";
original.style.display = "none";
}
});
deleteButtons[i].addEventListener("click", function() {
var result = [];
for (let x = 0; x < cards.length; x++) {
if (x == i) {
continue;
} else {
result.push(cards[x]);
}
}
reloadData(result);
});
}
});
<!DOCTYPE html>
<html>
<head>
<title>Memory cards</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>
<body>
<h1>Crea le tue memory card</h1>
<form>
<input type="text" id="txt1" name="txt1" placeholder="originale" />
<input type="text" id="txt2" name="txt2" plaecholder="traduzione" />
<input id="createCard" type="button" value="Crea" />
<input type="reset" value="Cancella" />
</form>
<div id="content">
<!-- inserisci le tue memory cards temporanee qua -->
</div>
</body>
</html>