Rahul
Rahul

Reputation: 11669

Simple Javascript highlighting in a text area?

I have two simple textareas where in i want to highlight the javascript code being written. As soon as the user types the function in the text area , the keywords etc have to be displayed in different color or so.

I tried to hack this script . But couldnt get what i wanted.

Upvotes: 8

Views: 9907

Answers (4)

I've always been interested in having textarea elements with added functionalities such as code highlighting, while still remaining as simple editable textareas. I've experimented a little bit here: http://www.dcc.uchile.cl/~jmunoz/

It's far from optimal and quite buggy, but still... It allows text highlighting using arbitrary rules. I used to have a working version which allowed to change the text color (And not just the background), but It had some issues.

Basically what I do is adding a div overlay with exactly the same content and font style as the text area but with transparent fonts. The text inside has span elements wrapping certain words and phrases which may have special backgrounds, borders, etc.

To allow for different font colors, I tried making the textarea text transparent while showing the overlay div text. The main issue there was that the cursor became transparent too.

I would say that using a div with editablecontent seems like a much better option.

Upvotes: 1

Ilia Sachev
Ilia Sachev

Reputation: 76

I think that you can use a div or section tag with content editable attribute. Inside this div or section you can use an additional markup for higlight functions, vars and etc. But this attribute work only in new browsers that support html5 attribute content editable. Here is a demo

If you need a simple js highligter, may be this one https://github.com/cloudhead/hijs is usefull for your task

Upvotes: 1

James Westgate
James Westgate

Reputation: 11444

Because a text area cannot contain markup, you cant so highlighting per se. The approach I used for an inline spell checker was to overlay divs for words that were spelled incorrectly. This was possible because it was possible to get the x and y location of words inside the text.

However it may be preferable to overlay the textarea with a content editable div which would allow you to wrap content in spans etc and then apply styling.

Upvotes: 0

Li0liQ
Li0liQ

Reputation: 11264

You could check Ace (demo) and CodeMirror (demo).

I suppose Textarea that can do syntax highlighting on the fly? and Online Code Editor questions will be useful for you as well.

Upvotes: 13

Related Questions