One <span> for each character in a text editor on the Internet
I am developing a text editor on web pages without any contentEditable , textarea or input stuff. The biggest part of my work is to measure the width of the text to the left (right) of the current carriage position and move the carriage in the text.
For example, when the user presses the DOWN key, the current offset to the left of the carriage should be calculated, and on the line below the character whose position most likely should be found.
One very convenient way is to use one DOM element for each character - I can just look at the offsetLeft property. In addition, carriage positioning is much easier. In fact, everything is simpler.
However, I am very unsure of the performance values . I saw this technique (or similar) used on some JavaScript IDE websites, and it works great there.
Do you have any clues, clues?
Do you know another quick way to measure text width. I want not to put sections of the line in the DOM element and measure its width every time, because I think it will be much slower.
EDIT: I basically ask about the basic EXISTENCE of many dom elements. How to make a measurement is another matter.
I saw this (unfortunately, I canβt find the link now) using the canvas object and the measureText () method - basically you can set the canvas "what size will this text fragment be if I displayed it in this style?" and use this to determine your carriage position on the surrounding lines. This works, but, of course, it will only work in browsers that support HTML5, and perhaps not all of them.
But frankly, it sounds like a big pain in the neck and probably more problems than it costs for the editor in the browser :)