The real answer is that the .slug() jQuery plug-in is quite poorly written. It's something like 20 lines of code and it's full of mistakes.
The proper place to fix this issue in in that plugin so it only has to be done once, not everywhere you use it. I would suggest changing that plug-in to this code which fixed a bunch of issues:
//
// jQuery Slug Generation Plugin by Perry Trinier ([email protected])
// Licensed under the GPL: http://www.gnu.org/copyleft/gpl.html
jQuery.fn.slug = function(options) {
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.
};
// merge options and settings
if(options) {
jQuery.extend(settings, options);
}
// save jQuery object for later use in callback
if (this.length > 0) {
var self$ = this.eq(0);
jQuery(document).ready( function() {
if (settings.hide) {
jQuery('input.' + settings.slug).after("<span class="+settings.slug+"></span>");
jQuery('input.' + settings.slug).hide();
}
self$.keyup(function() {
var slugcontent = jQuery(this).val();
var slugcontent_fixed = slugcontent.replace(/\s/g,'-').replace(/[^a-zA-Z0-9\-]/g,'').toLowerCase();
jQuery('input.' + settings.slug).val(slugcontent_fixed);
jQuery('span.' + settings.slug).text(slugcontent_fixed);
});
});
}
// return our jQuery object so it's chainable
return this;
};
This change fixes these issues with the prior code:
- It will now work properly if you call it on an empty jQuery object
- It will now work properly if called before the document is ready
- It is no longer making unnecessary calls to turn things into jQuery objects that are already jQuery objects
- If called on a selector with more than one object in it, it will only operate on the first item in the selector to prevent the problems that could occur otherwise
- Made the keyup callback an anonymous function rather than creating a new variable.
Note: This plug-in is written to only work with one slug field per page. As such, you should probably be using it with an id value like "#title" rather than a class name like ".title" because the id will never return more than one field and never get you into trouble that way.
I've verified that this code works here: http://jsfiddle.net/jfriend00/CJJGz/.