Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contenteditable, ::before selector styling and cursor position issue

Using a contenteditable div area, I am having issues (currently only tested in Chrome) where the cursor cannot be placed before the first letter of an inline styling element, when the CSS psuedo-selector ::before is used to add content before the "tag".

The use-case is this technique is used to display/style custom tags within a content editor. Each tag is indexed and this index is displayed to the left of the tag text.

Standalone example: http://codepen.io/TheFoot/pen/pydqQb

Thanks in advance..

EDIT: As @Sonny pointed out, if the embedded tag is display: block the problem goes away, but this breaks the need to highlight/style inline sections of text.

like image 911
TheFoot Avatar asked Sep 02 '25 02:09

TheFoot


2 Answers

Sounds like a little green bug drives you crazy eh? Anyway. I reckon you insert the TAG via javascript, so you must have some sort of function in place? One quick and dirty solution could be to ad an invisible character into that function before the tag opening. So e.g

<div class="tag" data-idx="6">&#x2063;maturity...</div>

Or you can just copy and paste the actual character (you can find between these arrows here:

--->⁣<---

As it's invisible it simulates exactly what you need.

[EDIT:]

If you want to reappend the invisible character in case the user deletes it. :)

$('.editor').keyup(function (e) { 
    if( e.which == 8 ) {
         $('.tag')
            .filter( (i,v) => { return $(v).text().match(/^⁣/) == null })
            .prepend("⁣")
    }
}) 

http://codepen.io/anon/pen/wddoBN

like image 62
ShQ Avatar answered Sep 04 '25 15:09

ShQ


I think the issue here is that the div that is contenteditable is inline-block. contenteditable should only be applied to block level elements (excluding headings).

A guideline a couple of people have mentioned is that only block-level elements should be made contenteditable. However, the Mozilla Developer Network lists the heading elements h1 through to h6 as block-level elements, and making a heading element contenteditable is buggy in Firefox4 and can crash the page in Chrome5.

You can read a little more information in this answer here: Which elements can be safely made contenteditable?

like image 25
Sonny Prince Avatar answered Sep 04 '25 14:09

Sonny Prince