Using ENTER for submit and SHIFT+ENTER for multi-line chat
If you've noticed on LinkedIn messaging when you chat with someone, you hit the ENTER key to send the message across and SHIFT+ENTER to enter a new line in the chat box. Most people aren't used to SHIFT+ENTER to go to the next line though.
This is pretty simple to replicate using AlpineJS. We listen to @keydown.shift
and @keyup.shift
where keyup / keydown are the keys that are pressed down or up respectively and .shift
is for listening specifically for the SHIFT key.
<textarea
@keyup.enter="
if (!shiftPressed)
{
chats.push($event.target.value);
$event.target.value = '';
}
"
@keydown.shift="shiftPressed = true"
@keyup.shift="shiftPressed = false"
placeholder="type your message here... and hit enter - hit SHIFT+ENTER to enter a new line"
rows="10" cols="50"
></textarea>
Using x-html
is dangerous but newlines in textarea
should be converted to HTML.
Here's the complete code.
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>AlpineJS Chat with Shift Enter</title>
</head>
<body>
<div x-data="{
shiftPressed: false,
chats: []
}">
<template x-for="chat in chats">
<div>
<div x-html="chat"></div>
<hr/>
</div>
</template>
<textarea
@keyup.enter="
if (!shiftPressed)
{
chats.push($event.target.value.replace('\n', '<br/>'));
$event.target.value = '';
}
"
@keydown.shift="shiftPressed = true"
@keyup.shift="shiftPressed = false"
placeholder="type your message here... and hit enter - hit SHIFT+ENTER to enter a new line"
rows="10" cols="50"
></textarea>
</div>
<script defer src="https://unpkg.com/alpinejs@3.13.2/dist/cdn.min.js"></script>
</body>
</html>
Demo : https://anjanesh.s3.amazonaws.com/demo/alpine/shift-enter.html
Subscribe to my newsletter
Read articles from Anjanesh Lekshminarayanan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Anjanesh Lekshminarayanan
Anjanesh Lekshminarayanan
I am a web developer from Navi Mumbai working as a consultant for cloudxchange.io. Mainly dealt with LAMP stack, now into Django and trying to learn Laravel and Google Cloud. TensorFlow in the near future. Founder of nerul.in