Reputation: 89
I have a div that is used as user input:
<div id="chat-message-input" contenteditable="plaintext-only">
When the user hits the enter key (and is not holding the shift key), the text from the user is submitted.
<script>
document.querySelector('#chat-message-input').onkeyup = function(e) {
// User hits enter key and is not holding shift
if (e.keyCode === 13 && event.shiftKey != 1) {
//Click submit button
document.querySelector('#chat-message-submit').click();
// Clear input field
document.getElementById('chat-message-input').innerHTML='';
};
</script>
Problem: There is a brief moment where the div creates a new line because the enter key was pressed, before the content in the div is cleared.
I only want a new line to be created under these circumstances:
Does anyone know how I can prevent a new line from being created given the above requirements?
Upvotes: 0
Views: 1045
Reputation: 89
As suggested by A Haworth, I also intercepted onkeydown (in addition to onkeyup) and prevented the default. This seemed to work well.
document.querySelector('#chat-message-input').onkeydown = function(e) {
// User hits enter key and is not holding shift
if (e.keyCode === 13 && event.shiftKey != 1) {
e.preventDefault()
}
};
This made the input field really solid, which is necessary for my real-time chat app. Thanks!
Upvotes: 0