Skip to main content

Command Palette

Search for a command to run...

Using ENTER for submit and SHIFT+ENTER for multi-line chat

Updated
1 min read
Using ENTER for submit and SHIFT+ENTER for multi-line chat
A
I am a web developer from Navi Mumbai. Mainly dealt with LAMP stack, now into Django and getting into Laravel and Cloud. Founder of nerul.in and gaali.in

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