Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking elements in contenteditable="true" div

I have a contenteditable div that's used for user input, when a button is clicked it shows options to replace certain words. First it strips away all html and creates span elements where a word can be replaced. The mark up of these words is different and I face some problems.

  1. When clicking directly before or after a span and typing text the text will have the same markup as the span. It's very hard to add words on a line that only has the span. I was thinking of solving this by padding the spans with   but it looks kind of strange.
  2. User can click in the span and change it, I would rather have the user click on the span and choose a replace or ignore option before changing it. In other words it needs to be locked. I was thinking of doing this by capturig keyup and if it comes from a span then e.preventDefault() on it but it's a bit of a pain to program it.

So my questions are:

Is there an easy way of locking a span element in a contenteditable that doesn't involve capturing key up and preventDefault (have not tried yet and not even sure if it'll work)?

When clicking or moving the cursor directly next to a span and typing text it'll be part of the span, is there a way to not have it be part of the span? Padding the span with   might work but it looks strange when the span is the first word on the line. To illustrate this I've posted an example html file below:

<!DOCTYPE html>
<html>
 <head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>Example</title>
</head>
 <body>
   <div contenteditable="true"></div>
   <script type="text/javascript">
    document.getElementsByTagName("div")[0]
      .innerHTML="<span style='color:green'>hello</span>"
   </script>
 </body>
</html>
like image 631
HMR Avatar asked Nov 02 '22 22:11

HMR


1 Answers

Mark the span inside your editable container contenteditable="false". It'll solve both problems at the same time.

like image 85
Yury Avatar answered Nov 11 '22 04:11

Yury