Saturday, 7 September 2013

Emulating syntax highlighting with Javascript

Emulating syntax highlighting with Javascript

I'm trying something out, just for a bit of fun really, whereby I'm trying
to emulate syntax highlighting when code is entered into a textarea on
webpage.
I've written a little JS script, but It's throwing errors. "cannot set
property 'color' of undefined."
To do this I have created a small array of a few example 'buzzwords' to
search the entered code for. Then I have split the code string into an
array and looped for matches between the two. I'm not that familiar with
the split method or indeed the search method. How can I get any matches
that are found to change colour on the screen in real time?
function init() {
window.setInterval(function() {
var code = document.getElementById("texty").value;
var buzzword =
["function","()","{","}","[","]",".getElementById",".getElementsByClassName",".style","$"];
for(i=0; i < buzzword.length; i++)
{
var testers = code.split(" ");
for(i =0; i < testers.length; i++)
{
if(buzzword[i] == testers[i])
{
code.search(testers[i]);
code.match(testers[i]).style.color = 'blue';
}
}
}
}, 10000);
}
function init() is executed onFocus of the textarea.
Any help would be appreciated, thanks!

No comments:

Post a Comment