A JS Fiddle of the plugin working
A contraction plugin for numerical values (ST,RD,TH).
I have been playing around with creating my own plugin, at the moment I’m just getting used to the syntax etc, this is just my playing with a script I needed and found today.
ok – my plugin should add th, st, rd etc on the end of any number with a span.num wrapped around it, the problem is for every number i need to call the plugin each time?
so I have two numbers, i need to give them both unique class names and then call my plugin (see fiddle)
my question: is it possible to only use one class name many times, and get back different results for each?
I’m thankful in advance for any replies and all apologies for my English today – brain fried!
$(document).ready(function(){
$(".num1").simpleContraction();
$(".num2").simpleContraction();
});
(function( $ ){
$.fn.simpleContraction = function() {
var num = this.text();
var len = num.length, last_char = num.charAt(len - 1), abbrev
if (len == 2 && num.charAt(0) == '1') {
abbrev = 'th'
} else {
if (last_char == '1') {
abbrev = 'st'
} else if (last_char == '2') {
abbrev = 'nd'
} else if (last_char == '3') {
abbrev = 'rd'
} else {
abbrev = 'th'
}
}
return this.html(num+abbrev);
};
})( jQuery );
You need to wrap a
this.each()block around your code so that each element in the jQuery collection is processed in turn:That said, I wouldn’t actually write this as a true plugin – it’ll have really nasty side effects if called on the wrong elements.
Instead, you can take advantage of the fact that
.textcan be passed a function that is passed the original text out of an element, and replaces it with the return value of that function:The advantage of this approach is that it separates the DOM manipulation from the string manipulation, and gives you a function that can be used on any string variable, and not just ones stored in the DOM.