Fri, October 30, 2020, 12:44:41
 
Home · Latest · Trends  /  JavaScript
1

Highlight.js Line Numbers

Highlight.js render line numbers via jQuery and CSS
//<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/default.min.css">
//<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>

//html:

//<pre><code class="php">Text</code></pre>

//style:

//code ul{counter-reset: line;}
//code li{counter-increment: line;}
//code li:before{content: counter(line);width: 30px;display: inline-block;}

$(document).ready(function() {
  $('pre code').each(function(i, e) {
    hljs.highlightBlock(e);
    var current = $(this),
      lineStart = parseInt(current.data('line-start')),
      lineFocus = parseInt(current.data('line-focus')),
      items = current.html().split("\n"),
      total = items.length,
      result = '<ul ' + (!isNaN(lineStart) ? 'start="' + lineStart + '"' : '') + '>';
    for (var i = 0; i < total; i++) {
      if (i === (lineFocus - lineStart)) {
        result += '<li>';
      } else {
        result += '<li>';
      }
      result += items[i] + '</li>';
    }
    result += '</ul>';
    var items = current.empty().append(result);
  });
});
rated 3 times [  2] [ 1]  / comments: 0 / hits: 2089  / 3 years ago, fri, jun 30, 2017, 04:04:58
More From » JavaScript
 

Comments

There are no comments for this Snippet yet
Username
 
Your Comment
 
Share
Posted
jimmy jazz

jimmy jazz

Member since Jun 30, 2017
Total Code Snippets: 1
Total Comments: 0
Location: n/a
Following
User not following anyone yet.