Stop contenteditable="plaintext-only" div from causing line breaks

I am currently facing an issue with a div element that serves as user input:

<div id="chat-message-input" contenteditable="plaintext-only">

Upon pressing the enter key (without holding down the shift key), the user's text gets 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>

Issue at Hand: A new line is briefly created in the div upon hitting the enter key, before the content within the div is cleared.

I would like a new line to be created only under the following conditions:

  1. The user's input text extends to the end of the line
  2. The user holds down shift while pressing enter

Is there a way to prevent the creation of a new line in accordance with the above requirements?

Answer №1

Following A Haworth's advice, I decided to also intercept the onkeydown event (in addition to onkeyup) and prevent the default behavior. Surprisingly, this strategy worked effectively.

    document.querySelector('#chat-message-input').onkeydown = function(e) {
       // When the user presses the enter key without holding down shift
       if (e.keyCode === 13 && event.shiftKey != 1) {
            e.preventDefault()
        }
    };

Implementing this approach has significantly improved the stability of the input field in my real-time chat application. Grateful for the suggestion!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to ensure one request completes before allowing another to be executed in Express/Node?

I am currently working on a task that involves fetching data from a third-party API (iTunes) to search for content provided by the API. The backend, which is handled by Express and Node, will interact with this third-party API. My goal is to trigger a POST ...

The 'import' statement is not functioning properly within a script in the rendered HTML

While working on an express application, I've encountered a recurring error that I can't seem to solve. The error message is: "GET http://localhost:3000/javascript/module2 net::ERR_ABORTED 404 (Not Found)" Could someone kindly assist me in ident ...

Is NextJS 13 the Key to App Directory On-Demand Revalidation?

I am looking to implement on-demand revalidation with next13 and the app directory. While I have successfully used the app-directory to replace the need for getServerSideProps or getStaticProps, there is one specific page on our site that needs to be rebui ...

Key steps for effectively implementing a Substring-Filter on a JSON array in d3

Trying to apply filtering on a JSON data array structured like this: var data = [ { "key": "FirstGroup", "color": "#1f77b4", "values": [ { "label ...

Tips on showcasing array elements within a table's tbody section and including several values within the same array

I am struggling to figure out how to display array values in my table rows that I receive from input values. I have created an array, but I can't seem to find a way to display them in the table. Furthermore, I want to be able to add more values to th ...

Engage with and rearrange JSON data

Upon receiving data from the endpoint, I realized that it needed some modifications before being suitable for display in a table. The initial example data looks like this: const data = [ { Year: 2017, OriginalIntBalanceOverdue: 0.0, D ...

Utilize jQuery to display or toggle each element individually, ensuring that only one is visible on the screen at any given time

Here are some clickable links: About Portfolio Resume Upon clicking 'About', I want the About section to appear while hiding the Portfolio and Resume sections (and vice versa)... This is how my code is structured (relevant parts only): HTML: ...

Attempting to display the contents of an array by iterating through it with a loop in a Angular JS using Javascript

I am attempting to display each item in an array that is a part of an object's property: { position: "Finance Office Assistant", employer: "Washtenaw County Finance Department", location: "Ann Arbor, MI", start_date: " ...

Issue with $_SERVER['PHP_SELF'] not functioning properly

Apologies if this question has been asked before, but after searching extensively I couldn't find a solution. Therefore, I am posting here... The issue is that I'm trying to submit values on the same page (using jQuery Mobile UI) and I have used ...

To center a div vertically within a Bootstrap 4.1 container-fluid > row > col, you can use the following method

I'm currently working on incorporating Bootstrap 4.1's align-middle into a col nested within a row. Despite my efforts, the content within is not aligning to the middle as expected. Take a look at my code below: <body class="d-flex"> < ...

Align the text in the center and the image to the right within a table cell <td>

Is there a way to keep text centered in a cell while right aligning an image within the same cell? When I use float:right on the image, it displays correctly but pushes the text to the left by the width of the image. Any solutions? <table> <tr ...

Steps to ensure buttons do not move along with the content scroll

How can I prevent buttons from scrolling with the content? Check out this Fiddle: http://jsfiddle.net/ravi1989/LegZv/1/ $(document).on('click', '.search_h', function() { $("#searchbar").toggle("slow"); }); I have tried using CSS ...

How can I convert a string containing only the time in the format HH:MM to a Date object in Javascript?

I've encountered an issue with a business hours object in a mongoose schema that is meant to represent a date. When passing a JSON object and attempting to parse it into a Date as a string, I receive an error message stating: validation failed: busine ...

What is the method for superimposing a div with a see-through input field?

I am currently designing a compact upload feature. It consists of a responsive element (actually a vue/quasar card) that adjusts in size according to the window dimensions and viewport. Within this element, there is a form containing an input field and a ...

Searching for Bluetooth devices using React Native

In my project, I am working on scanning HM-10 BLE with a react-native app. To achieve this, I referred to the example provided in Scanning for Bluetooth devices with React Native. So far, the library seems to be successfully installed without any errors du ...

Problem with ng-repeat not updating select dropdown options

Struggling with AngularJS while working on a project, I encountered an issue with a 'select-options' element. Currently, I am making a $http request to retrieve data from a Cloud SQL database. To achieve this, I am invoking a function from my f ...

"Transforming Selections in Illustrator through Scripting: A Step-by-Step Guide

In Illustrator, I successfully used an ExtendScript Toolkit JavaScript code to select multiple elements like text, paths, and symbols across different layers. Now, I am looking to resize them uniformly and then reposition them together. While I can apply ...

Can a button be created with multiple borders and a drop shadow effect?

I am trying to create this specific button using CSS https://i.sstatic.net/sLNzK.png (source: gyazo.com) Don't pay attention to the grey background I attempted cropping the center and adding border top, left, right, but it still looks odd. Do you ...

What is preventing this hover from activating the text animation?

Looking to create a hover effect in an CMS platform that only allows internal CSS styling. Despite the absence of a head tag, this CMS recognizes style tags and automatically inserts them into the template. After attempting to export as HTML to troublesho ...

Is there a way for me to confirm whether the response includes an array?

I need to enable the icon if there is an array present in the response. How can I verify the presence of an array in the response? Here's the code snippet I attempted: export function disableActions(name, data) { case i18next.t('abcd') ...