h

Loading...

 

Tuesday, February 23, 2010

syntax-highlighting with mootools

Fortunately I found this wonderful class which brings glance to my scripts. It's named "Lighter.js" and could be downloaded here ». It's based on the mootools-framework and is really simple to use.
I've taken these instructions from the Lighter-site. For detailed information about all the options you should have a look there. Simply place mootools-core and Lighter.js into your html-header-section.

<head>
 ...
 <script type="text/javascript" src="path_to_js/mootools.core.js"></script>
 <script type="text/javascript" src="path_to_js/Lighter.js"></script>
 ...
</head>

s
Prepare the code you wish to get "highlighted". Put it inside a pre-tag.
The class of the pre defines the language ('js') and which theme (':git') you'll like it to have.

<pre id="the_javascript_code" class="js:git"> 
 // just a bit of code for demo
 var test = "this is your testscript";
 alert(test);
</pre>

s
And finally just use the following function inside a ‘domready’- or ‘onLoad’-function to get your code highlighted.

// $('the_javascript_code') is the defined pre-element
// 'altLines' is just one of the options Lighter.js have
$('the_javascript_code').light({ altLines: 'hover' });

s
Done. Lighter cares about styles for you.
Highlight multiple elements
Because I'm too lazy to adress each single pre-tag with it's own id, I've done syntax-highlighting with a function, that uses an element-collection.

var convertSyntax = function (el) {
 var code = el.getElements('pre');
 if (code.length) {
  for (var i=0; i < code.length; i++) {
   code[i].getElement('code').light({
    // these are some of the options
    // 'Lighter.js' has to offer
    altLines: 'hover',
    indent: 2,
    mode: 'ol',     
    flame: 'git'
   });
  };
 };
};

// when all the content is loaded
// just call the function with the element containing
// all the pre-tags you'll want to get 'lighted'
window.addEvent('domready',function() {
 convertSyntax($('page_element')); // $('page_element') contains all pre-tags
});

s
As said, have a closer look at the pradador-site » for a much more detailed description or watch the demos » there.
requires: core lighter

No comments:

Post a Comment