Stop contenteditable from inserting a div element when the Enter key is pressed using only JavaScript, and

Is there a way to prevent the contenteditable feature from adding a div when Enter key is pressed, using pure JavaScript instead of jQuery?

I found an example that uses jQuery here: http://jsfiddle.net/uff3M/, but I specifically need a solution in plain JavaScript.

I managed to solve my issue. Thank you all for your help!

function enterToBr(e){
    var evt = e || window.event;
    var keyCode = evt.charCode || evt.keyCode;
    if(keyCode==13){
            document.execCommand('insertHTML', false, '<br>');
            return false;
    }
}
div{
    border:1px black solid;
    padding:10px;
}
<div contenteditable="true" id="container" onkeydown="enterToBr()">
When Enter is pressed, it currently creates a new div inside the container. However, I would like it to create a new line break (br element) instead.
</div>

Answer №1

It seems like the missing piece of the puzzle is ensuring that you properly stop the default action of the event - just using return false on its own may not suffice in this scenario.

To address this, you can propagate this return value through the HTML attribute used to attach the handler function,

onkeydown="return enterToBreak()"

Alternatively, you can thwart it by employing the suitable method,

    if(keyCode==13){
            document.execCommand('insertHTML', false, '<br>');
            evt.preventDefault();
    }

Answer №2

Another option is to utilize CSS for this task.

Incorporate display: inline-block; into your div element:

div{
    display: inline-block;
}

Answer №3

function convertEnterToBrTag(e){
    var event = e || window.event;
    var keyCodeVal = event.charCode || event.keyCode;
    if(keyCodeVal==13){
            document.execCommand('insertHTML', false, '<br>');
    }
}
div{
    border:1px black solid;
    padding:10px;
display: inline-block;
}
<div contenteditable="true" id="container" onkeydown="convertEnterToBrTag()">
When the Enter key is pressed, a new line break tag is created inside the container, rather than a new div element as currently happening.
</div>

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

Gap in footer spacing on Internet Explorer is significantly large

The layout of the page is split into two main sections: A large header that takes up 100% of the browser height The main content area and footer When viewing the page in a browser, only one of these sections will be visible. The following code works wel ...

What's the best way to animate the navigation on top of an image for movement?

I am currently in the process of creating my website as a graphic designer. My unique touch is having the navigation positioned on top of an image (which is animated via flash). This setup is featured prominently on my homepage, which is designed with mini ...

Necessary Selection from Dropdown

I've created a contact form with both optional and required fields. One of the mandatory fields is a drop-down menu, which looks like this: <div> <select name="favFruit[]" size="1" required> <option value="apple">Apple&l ...

Converting large numbers (exceeding 53 bits) into a string using JavaScript

I have a REST service that returns JSON. One of the properties in the JSON contains a very large integer, and I need to retrieve it as a string before Javascript messes it up. Is there a way to do this? I attempted to intercept every response using Angular ...

Saving data to a variable with AJAX/JSON when the column name is numerical: Best practices

When attempting to save a JSON value as a variable from an AJAX response ... $.ajax({ url:'example.php', type:'POST', dataType: 'json', success:function(data){ var checkname = data.name; // works fine var check1m = ...

Mismatched Container Alignment in HTML and CSS

I am struggling to position the timeline next to the paragraph in the resume section, but it keeps appearing in the next section or below where it's supposed to be. I want the timeline to be on the right side and the heading/paragraph to be on the lef ...

Is it possible to utilize the package.json "resolutions" field to replace lodash with lodash-es?

Is it possible to use resolutions in a similar manner as dependencies, but with a different package? I'm specifically curious if this can be done with NPM or Yarn. "resolutions": { "lodash": "npm:lodash-es@^14.7.x" ...

Is there a way to use JavaScript to convert HTML code into plain text?

I am looking to convert an input from an API in the following format: <p>Communication that doesn&#8217;t take a chance doesn&#8217;t stand a chance.</p> into something like this "Communication that doesn’t take a chance do ...

The use of Angular's ngClass directive does not work within the link function

I have a straightforward directive that renders an element, and this is the template: <div class="nav-item"></div> The .nav-item class looks like this: .nav-item { height: 50; } Here's the directive in action: angular.module('m ...

What is the best way to manage executing functions on data that could potentially be undefined?

When working with React, I often encounter the need to write functions that rely on a component's state. One common issue I face is the necessity to check if a piece of state is defined before proceeding with any actions. For instance, I have a funct ...

MySQL field being updated upon page unload

I'm currently developing a Content Management System (CMS) that allows users to access and organize records within a MySQL database. One of the features I have implemented is a user login system for the CMS. As part of this project, I am working on in ...

Getting an array of all visible text on a page using the same locator in Selenium

Within different sections of the webpage, I have utilized the following locator (excerpt from HTML): <table id="userPlaylistTable" cellspacing="0" cellpadding="0"> <p class="title"> ABC </p> <p class="title"> DEF </p> ...

Executing the split function on a 2D array in Google Apps Script while maintaining the original column indexing

When running the split function on an array column in Google Apps Script, it generates multiple columns with varying numbers. Some rows may have 6 columns and others only 4. I want to adjust the output array to ensure all rows have an even number of colum ...

Unable to display Bootstrap 4.3.1 button for Facebook

I'm attempting to incorporate Bootstrap 4.3.1 into my Asp.net Core MVC project, but it appears to be not working. Any suggestions? <!doctype html> <html lang="en"> <head> <link rel="stylesheet" href="https ...

Error: An unexpected closing tag "<p>" was encountered while parsing the template

I am facing an issue while trying to format an XML file in Angular. Here is the code snippet I attempted to use: <div class="element-box"> <div class="details-wrapper"> <p><b class="label">Raw Request</b> <pre& ...

Tracking user engagement and traffic on a website with a single tracking ID for both screenviews and pageviews

I'm facing an issue while attempting to send screenviews and pageviews using the same tracking ID in my AngularJS web app. The error message I keep encountering is as follows: Access denied. Please try relaunching In-Page Analytics from the report. ...

Transforming AngularJS $http POST requests into GET requests

I came across a scenario where I needed to update the logo path in my application. So, I defined a route like this: Route::post('/updateLogo', 'CaptivePortalController@updateLogo'); After defining the route, I made a POST request as s ...

Develop two varieties of user account models using Mongodb/Mongoose

Currently, I am utilizing mongoose in my nodejs project and I am seeking advice on creating a MongoDB schema that caters to two different user types: employees and clients. Both of these users will be registering through the same page (I am implementing pa ...

Encountering difficulty in accessing game.html following button clicks

Why isn't the redirection to game.html happening after clicking on the buttons in index.html? The file structure consists of server/server.js, public/index.html,public/game.html. <!DOCTYPE html> <html> <title>QUIZ GAME</title ...

Tips for retrieving values from numerous checkboxes sharing the same class using jQuery

Currently, I am struggling with getting the values of all checkboxes that are checked using jquery. My goal is to store these values in an array, but I am encountering difficulties. Can anyone provide me with guidance on how to achieve this? Below is what ...