$.gist demo
by benjamine
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>$.gist test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
</head>
<body>
<h1>$.gist demo</h1>
<p>This demo contains some gist links that will be converted to embedded gist on document load</p>
<a href="https://gist.github.com/999085#file_README.mdown">view README</a>
<p>Here's a $.gist example html:</p>
<a href="https://gist.github.com/999085#file_test.html">view html</a>
<script type="text/javascript">
$($.gist); // replace gist links by embedded gists
</script>
</body>
</html>
JavaScript
(function($) {
var count = 1,
stylesheets = {},
gistUrlRegex = new RegExp('^(https?://)?gist.github.com/([0-9]+)(#file_(.*))?$');
$.gist = function(id, file, placeholder) {
if (!id || id === $) {
// no arguments, replace all anchors in document
$(document).gist();
} else {
placeholder = placeholder || ['gist', id, count++].join('-');
$('<div />', {
'id': placeholder
}).appendTo('body').gist(id, file);
}
};
$.gist.url = function(id, file) {
var $this;
var https = false;
if (!id && ($this = $(this)).is('a')) {
// no id specified, get from anchor href
var match = gistUrlRegex.exec($this.attr('href'));
if (match) {
https = match[1] == 'https://';
id = match[2];
file = match[4] || file;
}
} else if (typeof id == 'object') {
file = typeof id.file == 'function' ? id.file.apply(this) : id.file;
id = typeof id.id == 'function' ? id.id.apply(this) : id.id;
}
if (!id) {
return null;
}
var url = (https ? 'https' : 'http') + '://gist.github.com/' + id + '.json?';
if (file) {
url += 'file=' + file + '&';
}
url += 'callback=?';
return url;
};
$.fn.gist = function(id, file) {
if (!id && !this.is('a')) {
// container and no parameters, call on contained anchors
return this.find('a').gist();
}
for (var i = 0, l = this.length; i < l; i++) {
var self = this[i];
var url = $.gist.url.apply(self, arguments);
if (url) {
$.ajax(url, {
dataType: 'json',
context: self,
success: function(json) {
// embed gist
...