Skip to content

Instantly share code, notes, and snippets.

@ntulip
Forked from arunthampi/jquery.slug.js
Created May 25, 2010 16:08
Show Gist options
  • Save ntulip/413325 to your computer and use it in GitHub Desktop.
Save ntulip/413325 to your computer and use it in GitHub Desktop.
//
// jQuery Slug Generation Plugin by Perry Trinier (perrytrinier@gmail.com)
// Licensed under the GPL: http://www.gnu.org/copyleft/gpl.html
jQuery.fn.slug = function(options) {
// Only do something if the element exists
if(this.length != 0) {
var settings = {
slug: 'slug', // Class used for slug destination input and span. The span is created on $(document).ready()
hide: true // Boolean - By default the slug input field is hidden, set to false to show the input field and hide the span.
};
if(options) {
jQuery.extend(settings, options);
}
$this = $(this);
$(document).ready( function() {
if (settings.hide) {
$('input.' + settings.slug).after("<span class="+settings.slug+"></span>");
$('input.' + settings.slug).hide();
}
});
makeSlug = function() {
var slug = jQuery.trim($this.val()) // Trimming recommended by Brooke Dukes - http://www.thewebsitetailor.com/2008/04/jquery-slug-plugin/comment-page-1/#comment-23
.replace(/\s+/g,'-').replace(/[^a-zA-Z0-9\-]/g,'').toLowerCase() // See http://www.djangosnippets.org/snippets/1488/
.replace(/\-{2,}/g,'-'); // If we end up with any 'multiple hyphens', replace with just one. Temporary bugfix for input 'this & that'=>'this--that'
$('input.' + settings.slug).val(slug);
$('span.' + settings.slug).text(slug);
}
$(this).keyup(makeSlug);
return $this;
} else {
return this;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment