Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML/CSS/JS: How to make an illusion of a textarea with line numbers?

I want to have a textarea which displays line numbers on the left. Wrap should be set to "off" (so that horizontal scrolling is available). I want to have my page as a single self-contained .html file (there will be no graphics), so I'd like to avoid any 3rd party frameworks.

Which way should I go? How would you do this?

like image 671
Vilx- Avatar asked Dec 15 '09 13:12

Vilx-


2 Answers

I would start with two text-areas and synchronzation mechanism. Something like this,

    <script>
    window.sync = function(e){
            var textarea = document.getElementById("lines");
            var source   = document.getElementById("some_text_area");
            textarea.scrollTop = source.scrollTop;
        }

        window.populate = function populate(){
            if(populate.started){
                return;
            }

            populate.started = true;
            var textarea = document.getElementById("lines");
            var str = '';
            for(var i=0;i < 100;i++){
                str = str + (i +'\r\n');
            }
            textarea.value = str;
        }
    </script>

<div>
<textarea 
    style="width:40px;overflow:hidden;height:40px;" 
    readonly="true" 
    id="lines"
></textarea>
<textarea 
    style="width:500px;height:40px;" 
    id="some_text_area" 
    onclick="populate()"
    onscroll="sync();"
></textarea>
</div> 

Ofcourse populate() function (and the style declaration and event declaration) should be more robust and intelligent, , but, it just for showcase purpose.

like image 122
nemisj Avatar answered Nov 15 '22 00:11

nemisj


I think your best bet would be to just have a regular textarea, and show a preview (like stack overflow) as they type along. Within that preview, you could easily add line numbers on each line and format the look via CSS.

like image 21
Zack Marrapese Avatar answered Nov 15 '22 00:11

Zack Marrapese