Tips for avoiding deleting content within a span element when using contenteditable

I am working on an HTML 5 editor that utilizes the contenteditable tag. Inside this tag, I have a span. The issue arises when all text is removed as the span also gets removed. I want to prevent the removal of the span, how can I achieve this?

Here is a snippet of my code:

$('#editor').keyup(function(){
  $('#spanText').text($(this).find('span').text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div contenteditable="true" id="editor"><span>This is my text</span></div>

<br><br><hr>
<div id="spanText"></div>

Answer №1

It seems like achieving that goal is not as simple as we thought.

If you want to revert the element back, consider checking its text length.

Take a look at this demo:

$('#editor').keyup(function(){
  if(!$(this).text().length){
    $(this).html('<span>&nbsp;</span>');
  }
  $('#spanText').text($(this).find('span').text().trim());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <div contenteditable="true" id="editor"><span>This is my text</span></div>
</div>
<hr>
<div id="spanText"></div>

Answer №2

Transfer the contenteditable attribute to the span element

<div>
   <span id="editor" contenteditable="true">This is my text</span>
</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

CSS and HTML modal not closing

I've been working on creating a custom popup using HTML, CSS, and some jQuery functions. My idea was that when I click on the main div, it should expand in size and display a cancel button, which it does successfully. However, the issue arises when tr ...

Utilizing em units within CSS media queries is producing erratic outcomes on various browsers

My CSS media queries are set up in a progressive manner like the following: * { font-size: 14pt; } @media screen and (min-width:85em) { : : } @media screen and (min-width:110em) { : : } When I have two browsers open on the same screen, with identical siz ...

Issue with konvaJS when trying to simultaneously resize, drag, and apply filters to an image

Looking for help with resizing, dragging, and filtering images using Konvajs 2d canvas library? If the images are not resizing properly after applying a filter, can someone assist me? Note: Please be aware that when using Google image URLs, there may be c ...

Managing a collection of input values

Is there a way to effectively manage an array of input fields using reactjs? Take for instance this text field: <input type="text" value="" name="test[]" /> Below is the code I'm currently working with: render () { ...

Incorporating Past Projects into an Angular 2 Website

Some time ago, I built a Javascript game utilizing the HTML canvas element for image rendering. Now that I have a personal website created with Angular 2, I am unsure of how to properly embed my game into my site. Due to Angular 2 removing the script tag ...

Unable to replace default typography in MUI with custom typography theme on Next.js

In my Next.js React project, I am utilizing Material-UI (MUI) with a customized theme. Although the colors from the theme are being applied successfully, I am encountering difficulty in adjusting the default font sizes of H2 and H5 elements. Even though I ...

Using Javascript's OnChange event to dynamically update data

Attempting to achieve a seemingly straightforward task, but encountering obstacles. The goal is to trigger a JavaScript onChange command and instantly update a radar chart when a numerical value in a form is altered. While the initial values are successful ...

Is there a way to prevent the URL of my Next.js app from constantly changing?

Our current Next.js project requires that the static URL remains constant, even when navigating between pages. This is a client requirement that we must adhere to. Can you provide suggestions on how we can achieve this? Maintaining the same URL throughout ...

PHP and JavaScript: Understanding Variables

I currently have a View containing an Associative Array filled with information on accidents. Users will have the ability to click on a Country. Once clicked, I want to display accident-related data for that specific country. This data is pulled from PHP ...

Check the input text using jQuery with various validation criteria

When I enter an alphanumeric code into a form, I need to validate it. After entering the code and clicking on the submit button: If there is an error in the text, an error message will be displayed. else a success message will appear upon submis ...

The Challenge of CSS Transition and Checkbox Label Discrepancies

I'm looking to adjust the position of my label when a checkbox is checked. Everything works smoothly if I don't include a transition for the top offset property in the CSS of my label. However, when this transition is added (as seen in the commen ...

The Countdown Timer in React Native triggers an error due to Invariant Violation

According to some expert advice from this stackoverflow answer, I attempted to implement a countdown timer for my project as shown below. constructor(props: Object) { super(props); this.state ={ timer: 3,hideTimer:false} } componentDidMount(){ this. ...

Incorporate Ruby's embedded helpers with jQuery for advanced functionality

How do I properly add a ruby helper to iterate through an active record response? I attempted to do so with the following code (.html or .append): $( ".result" ).html('<%= @products.each do |product| %><label>product</label><% e ...

Exploring the ins and outs of utilizing pseudo selectors with material-ui

I've been attempting to accomplish a simple task. I wanted to toggle the visibility of my <TreeMenu/> component in material UI v1 using pseudo selectors, but for some reason it's not working. Here is the code: CSS: root: { ba ...

Creating multiple rectangles and filling them with a color chosen by the user in Angular can be achieved by following these steps

Looking for advice on angular coding. I'm working on a project that requires creating multiple rectangles and filling them based on selected values. Can anyone suggest a module that would offer this functionality? ...

Any ideas on how to format a date for jQuery Datepicker?

Currently, I have implemented two different datepickers on my website, but I am interested in switching to jQuery's Datepicker for a more unified solution. Here is the current format that I am sending to our backend API: However, I would prefer to i ...

Scraping the web using Python for HTML data retrieval

I'm working on a Python program to retrieve the card sub-brand and brand based on a card BIN number. The URL for this information is: . The code snippet below fetches the card type from the page. page = requests.get('https://www.cardbinist.com/s ...

Transferring an array from PHP to jQuery through the use of AJAX

My JavaScript code communicates with a PHP page to retrieve data from a database and store it in an array. Now, I would like to use jQuery to loop through that array. This is how the array is structured: Array ( [0] => Array ( [image] => articl ...

Issue with Promise failing to trigger .then() following fetch to Express API/Mongoose request

Can someone shed light on why I am unable to return a promise and invoke .then() on it? I am creating an inventory system for my collection of Pokemon cards using a react front-end and an express backend. When I click the "increase inventory" button on th ...

Utilizing a React hook within an event listener

I have developed a custom hook for playing audio in react, here is the code: "use client"; import { useEffect, useState } from "react"; export const useAudio = (url: string) => { const [audio, setAudio] = useState<HTMLAudioE ...