I'm actually learning since two month so excuse-me if it seems really dumb when I'm asking this question but : Why is my function is running exponentially each time I use it?
const textArea = document.querySelector('.messenger__text-area')
const input = document.querySelector('.messenger__input')
function addText() {
input.addEventListener('keypress', function (e) {
if (e.keyCode === 13) {
textArea.innerHTML += `<div class='message__sent'>${input.value}</div>`
input.value = null
}
});
}
I'm working on chatroom and I just want this div to be displayed in the text area, which works, kinda but each time I press enter to send the input value into the text are it makes too much copy of the empty div "message__sent". Seems like if I put more letter, more "phantom" divs are created.
I just want it to be created one single time when I press enter, how do you think I could do that?
Thanks for your answers, I really couldn't find anything on the internet to help me so here I am.
(i'll share the html with you below so you can feel free to test if you want)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Afpa'car Chatroom</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@400;600;700&display=swap"
rel="stylesheet">
<link rel="stylesheet" href="../index.css">
</head>
<body>
<header>Header</header>
<div class="hr-large--grey"></div>
<main>
<div class="messenger">
<div class="messenger__contact">
<div class="messenger__contact--return">
<a href="../index.html">
<
</a>
</div>
<div class="messenger__contact--name">
<h2>
Placeholder Contact
</h2>
</div>
<div class="messenger__contact--status">
●
</div>
</div>
<hr class="hr-large" />
<div class="messenger__text-area">
Placeholder Text
</div>
<hr class="hr-large" />
<input class='messenger__input' onkeypress='addText()' placeholder="Ecrivez un message..."></input>
</div>
</main>
<div class="hr-large--grey"></div>
<footer>Footer</footer>
<script src="../index.js"></script>
</body>
</html>