Enclose the text entered by the user within a newly created element inside a contentEditable division

My current setup includes a contentEditable div like this:

<div id="content" contentEditable="true"></div>

What I want to achieve is for any text typed by the user to be automatically wrapped within div or p tags. While I can add HTML code to the "content" div, the typing itself occurs outside of the created element.

function keyPress(e) {
    if (e == 'undefined') e = window.event;
    var target = e.target || e.srcElement;
    if (e.keyCode === 13) {
        //close the div or p tag or just exit out of it
    }
}
function mainFocus(e) {
    if (e == 'undefined') e = window.event;
    var target = e.target || e.srcElement;
    if (!target.innerHTML) {
        //var div = document.createElement("div");
        //$id("content").appendChild(div);
        //or $id("content").execCommand("insertHTML", false, "div");
        //inserts the div but typing is outside the newly created tag
    }
}

Currently, text entered inside the div does not get wrapped with tags until Enter is pressed for a new line. My goal is to wrap the initial text as well and ensure that previous text ends with a closing tag when inserting an image. This behavior is observed in Chrome, and I'm still exploring the potential of contentEditable div elements.

UPDATE: After further experimentation, I am comfortable with the functionality of the contentEditable field. My only concern remains that the initial text lacks enclosing tags, which are added automatically for subsequent lines. How can I enclose the first line of text within div tags while maintaining standard functionality?

Answer №1

I found a workaround that might not be perfect, but it involves disabling the default functionality of contentEditable and wrapping everything onblur:

function keyPress(e) {
            if (e.keyCode === 13) {
                document.execCommand("insertHTML", false, "<br><br>");
                return false;
            }
        }
        function wrapText(_callback) {
            var target = $id("content");
            for (var i = 0; i < target.childNodes.length; i++) {
                (function(i) {
                    var curNode = target.childNodes[i];
                    if (curNode.nodeName === "#text") {
                        var element = document.createElement("span");
                        element.setAttribute("id", i);
                        target.insertBefore(element, curNode);
                        element.appendChild(curNode);
                    }
                })(i);
            }
            _callback();

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

Tips for posting a data-uri image on Pinterest

I'm attempting to post a data-uri image on Pinterest. Here is the code I am using: <a target="_blank" href="https://www.pinterest.com/pin/create/button/"> <img class="pin-image" src="data:image/png;base64,…"> </a> Following th ...

Help with CSS and React - how to position text in front of an image

Currently, I am working on positioning text on top of an image and centering it within the parent div. You can see the desired design in the screenshot below: https://i.sstatic.net/NNidz.png After experimenting with code and using z-index to layer the te ...

Issue: A script tag containing a defer attribute cannot also include a type attribute set to module

My website code includes the following script in the <head>-section: <script defer src="./static/js/main.js" type="module"></script> When I ran my code through the validator on validator.w3.org, it flagged an error sa ...

Eliminate any <div> tags that contain matching patterns in their ids

All the div elements are nested inside another div with the ID #main. The structure resembles a tree, with each div connected to its parent by a single line. These div elements are dynamically generated, and their IDs are created following a specific patte ...

Encountering a SyntaxError: Unexpected token < in the initial position of JSON during JSON parsing within Node.js

const express = require("express"); const bodyParser = require("body-parser"); const request = require("request"); const https = require("https") ; const app = express(); // store static files (e.g css,image files) ...

Display a progress bar in an application to visualize the loading of database records

Within my application, I am accepting a numerical input that is used to generate results on a separate page. The process involves running multiple sequential JDBC queries against Oracle database tables, resulting in a significant delay (1-2 minutes) for th ...

Create a functional component in React.js and Material-UI to display data

I am facing an issue with data management, where multiple titles are being rendered in my table when trying to display data from the Pokemon API. I attempted to move only the data to a separate component but was unsuccessful. Any suggestions on how to res ...

Utilizing props to define the background-color of the '&:hover' state

I'm adapting Material UI's Chip component to accept custom values for the colors prop, rather than being limited to "primary" and "secondary". Additionally, I want the chip to exhibit a hover effect when clicked, transitioning to a different colo ...

How can the default text color be adjusted in NSAttributedString when initialized with HTML dark mode?

During the process of converting my existing app to dark mode, I came across an instance where I needed to initialize a UITextView with an NSAttributedString for displaying some legal text from the app store. While everything looked good in light mode, swi ...

Functionality of selecting dates using a datepicker

Currently, I have a single-page web app that includes a datepicker function in the HTML. However, I am facing an issue where the date field remains selectable even when the page is loading to fetch data from the backend (DB). This results in the user bei ...

Hover over a link to split it into two separate links

I'm attempting to create a link that transforms into two separate links when the text is hovered over. An example of what I am trying to achieve can be seen here: . This website showcases how the 'collections' link splits into two distinct l ...

Maintain the modifications in NPM software dependencies

Currently, I am developing a REACT web application and have integrated the react-datasheet library using NPM. To ensure compatibility with IE11, I made modifications to the JavaScript file installed via NPM. While these changes work perfectly on my local m ...

Storing data or a page in a list within a React Native application

As a newcomer to React Native, I'm facing an issue. I have two pages called rockSetting.js and myFavoriteSetting.js. In the rockSetting page, I want to implement an onButtonPress function that will generate a list in the myFavoriteSettings page with ...

Requesting data from the application to the MongoDB database is currently malfunction

Currently, I'm utilizing Express and passport to develop an application. Everything has been going smoothly so far, but I've encountered a problem when attempting to retrieve data from my mongo database. Strangely enough, I am able to successfull ...

What is the best method for inserting space between two divs?

I need to create more space between the last two cards and the image at the bottom, but this spacing should increase as I resize the browser window. Can anyone help me with this? https://i.stack.imgur.com/rq9t2.png https://i.stack.imgur.com/tOikx.png Th ...

What is the best way to retrieve the slot object property in order to send it to a component for a specific data table row in Vuet

I have defined a vue data property as shown below: data() { orders: [], order: { order_id: null length: null, width: null, } } Additionally, I have implemented a vuetify data table structured like this: <v-data-table v-if=& ...

Is it possible to show or hide a DIV based on the text content of another DIV using JavaScript in

I am looking for a way to dynamically hide a DIV based on user roles using only the text inside a title tag as a reference. Here is an example of the HTML structure: <title>admin</title> If the user role is admin, then hide the following DI ...

Deleting content in a text area when specific text is entered

Is there a way to clear the textarea value if I type in <br>? The code I have right now is shown below. I understand that this may seem like an odd request, but I am experimenting with a typing effect. function eraseText() { document.getElemen ...

Prevent automatic jumping to input fields

Can someone help me with a problem related to the html input tag or primefaces p:input? I am facing an issue where the cursor always automatically jumps into the input field. The height of my page is such that scrolling is required, and the input field i ...

What is the best way to streamline the creation of a "products filter" using Node.js and Angular?

I have decided to build an angular application for an online computer store, and I am using a node/express backend. One of the key features of the application is the products page, where users can view all the products available in our database. Each produ ...