Showing HTML Code on a Web Page
By Forrest Smith - Drempd.com
There is obviously a need a site like this to show HTML code within a blog post. Recently the need for this functionality also arose at work, so I decided to put together a quick script to make the task easier. This will scan for a tag with the class of code (ideally a ‘pre’ tag, but can be whatever). You just have to insert the html code that you want to show to your website visitors within that ‘pre’ tag. The script will then convert all of the special characters so they will render correctly. This just requires jquery to be included on the page:
Javascript Code:
$(function () { Format_Code(); }); function Format_Code() { //Convert special characters: $(\'.code\').each(function (i, obj) { var content = $(this).html(); content = content.replace(/</g, "<"); $(this).html(content); }); //Realign everything so the first line of code is left-aligned and relative to this (): [].forEach.call(document.querySelectorAll(\'pre\'), function ($pre) { var lines = $pre.textContent.split(\'n\'); var matches; var indentation = (matches = /^s+/.exec(lines[0])) != null ? matches[0] : null; if (!!indentation) { lines = lines.map(function (line) { return line.replace(indentation, \'\'); }); return $pre.textContent = lines.join(\'n\').trim(); } }); }
-
Adventure
-
The Built Environment
-
Locations
-
Web Dev