Created
February 23, 2012 20:10
-
-
Save jcreamer898/1894821 to your computer and use it in GitHub Desktop.
jQuery slugify a url
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function ($, window, document, undefined) { | |
// Define the jQuery plugin name and some default options | |
var pluginName = 'slugify', | |
defaults = { | |
on: "blur", | |
prefix: '' | |
}; | |
// The actual plugin constructor | |
function Slugify(element, options) { | |
this.element = element; | |
this.options = $.extend({}, defaults, options); | |
this._defaults = defaults; | |
this._name = pluginName; | |
this.init(); | |
} | |
Slugify.prototype.init = function () { | |
var events = this.options.on.split(' '), | |
self = this; | |
// Space de-limited list of events, "keyup blur keydown". | |
// Bind the events to the slugTo function | |
$.map(events, function(e) { | |
$(self.element).bind(e, $.proxy(self.slugTo, self)); | |
}); | |
}; | |
// Slug the field that the plugin is attached to, | |
// and place the result in some other field defined | |
// by the slugTo option. | |
Slugify.prototype.slugTo = function(event) { | |
var thisElement = $(this.element), | |
text = thisElement.val(), | |
element; | |
text = text.toLowerCase(); | |
text = text.replace(/^\s+|\s+$/g, ''); // trim | |
text = text.replace( /[^a-zA-Z0-9]+/g , '-'); | |
text = text.replace( /\-+$/g, ''); | |
this.text = text; | |
// Store the slug on the data for the DOM element being used | |
thisElement.data('slug', this.text); | |
if(this.options.slugTo) { | |
if(typeof this.options.slugto === 'object') { | |
element = this.options.slugto; | |
} | |
else { | |
element = $(this.options.slugTo); | |
} | |
} | |
else { | |
element = thisElement; | |
} | |
if(element) { | |
element.val(this.options.prefix + this.text); | |
} | |
}; | |
// Expose the plugin to jQuery | |
// http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/ | |
$.fn[pluginName] = function(options, arg) { | |
return this.each(function() { | |
if(typeof options === 'object' || typeof options === 'undefined'){ | |
if (!$.data(this, 'plugin_' + pluginName)) { | |
$.data(this, 'plugin_' + pluginName, | |
new Slugify( this, options )); | |
} | |
} | |
else if(typeof options === 'string'){ | |
var plugin = $.data(this, 'plugin_' + pluginName); | |
if(typeof plugin[options] === 'function'){ | |
plugin[options](arg); | |
} | |
else{ | |
throw('Invalid method: ' + options + ' called on plugin: ' + pluginName); | |
} | |
} | |
}); | |
}; | |
})(jQuery, window, document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment