Skip to content
  • home
  • portfolio
  • web design journal
  • blog
    • adventure
    • san diego
    • projects
    • website design
Blog Web Dev Showing HTML Code on a Web Page

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();
			}
		});
}
Posted on January 31, 2015August 26, 2022 in Web Dev
  • Adventure

    • adventure
    • gravelgrinding
    • hiking
    • running
  • The Built Environment

    • architecture
    • urbanity
  • Locations

    • san diego
    • portland
  • Freelance Life

    • freelancing
    • productivity
  • Web Dev

    • css
    • entrepreneurship
    • git
    • handlebars
    • html
    • inkscape
    • photoshop
    • php
    • sass
    • web design
    • web development
    • saphire

drempd | san diego, ca


home contact

adventures san diego urbanity and architecture projects stream website design

portfolio resume san diego web design freelance web designer

custom web design responsive web design website maintenance