jquery.rateit.js
16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*! RateIt | v1.0.22 / 05/27/2014 | https://rateit.codeplex.com/license
http://rateit.codeplex.com | Twitter: @gjunge
*/
(function ($) {
$.rateit = {
aria: {
resetLabel: 'reset rating',
ratingLabel: 'rating'
}
};
$.fn.rateit = function (p1, p2) {
//quick way out.
var index = 1;
var options = {}; var mode = 'init';
var capitaliseFirstLetter = function (string) {
return string.charAt(0).toUpperCase() + string.substr(1);
};
if (this.length === 0) { return this; }
var tp1 = $.type(p1);
if (tp1 == 'object' || p1 === undefined || p1 === null) {
options = $.extend({}, $.fn.rateit.defaults, p1); //wants to init new rateit plugin(s).
}
else if (tp1 == 'string' && p1 !== 'reset' && p2 === undefined) {
return this.data('rateit' + capitaliseFirstLetter(p1)); //wants to get a value.
}
else if (tp1 == 'string') {
mode = 'setvalue';
}
return this.each(function () {
var item = $(this);
//shorten all the item.data('rateit-XXX'), will save space in closure compiler, will be like item.data('XXX') will become x('XXX')
var itemdata = function (key, value) {
if (value != null) {
//update aria values
var ariakey = 'aria-value' + ((key == 'value') ? 'now' : key);
var range = item.find('.rateit-range');
if (range.attr(ariakey) != undefined) {
range.attr(ariakey, value);
}
}
arguments[0] = 'rateit' + capitaliseFirstLetter(key);
return item.data.apply(item, arguments); ////Fix for WI: 523
};
//handle programmatic reset
if (p1 == 'reset') {
var setup = itemdata('init'); //get initial value
for (var prop in setup) {
item.data(prop, setup[prop]);
}
if (itemdata('backingfld')) { //reset also backingfield
var fld = $(itemdata('backingfld'));
fld.val(itemdata('value'));
fld.trigger('change');
if (fld[0].min) { fld[0].min = itemdata('min'); }
if (fld[0].max) { fld[0].max = itemdata('max'); }
if (fld[0].step) { fld[0].step = itemdata('step'); }
}
item.trigger('reset');
}
//add the rate it class.
if (!item.hasClass('rateit')) { item.addClass('rateit'); }
var ltr = item.css('direction') != 'rtl';
// set value mode
if (mode == 'setvalue') {
if (!itemdata('init')) { throw 'Can\'t set value before init'; }
//if readonly now and it wasn't readonly, remove the eventhandlers.
if (p1 == 'readonly' && p2 == true && !itemdata('readonly')) {
item.find('.rateit-range').unbind();
itemdata('wired', false);
}
//when we receive a null value, reset the score to its min value.
if (p1 == 'value') {
p2 = (p2 == null) ? itemdata('min') : Math.max(itemdata('min'), Math.min(itemdata('max'), p2));
}
if (itemdata('backingfld')) {
//if we have a backing field, check which fields we should update.
//In case of input[type=range], although we did read its attributes even in browsers that don't support it (using fld.attr())
//we only update it in browser that support it (&& fld[0].min only works in supporting browsers), not only does it save us from checking if it is range input type, it also is unnecessary.
var fld = $(itemdata('backingfld'));
if (p1 == 'value') { fld.val(p2); }
if (p1 == 'min' && fld[0].min) { fld[0].min = p2; }
if (p1 == 'max' && fld[0].max) { fld[0].max = p2;}
if (p1 == 'step' && fld[0].step) { fld[0].step = p2; }
}
itemdata(p1, p2);
}
//init rateit plugin
if (!itemdata('init')) {
//get our values, either from the data-* html5 attribute or from the options.
itemdata('min', isNaN(itemdata('min')) ? options.min : itemdata('min'));
itemdata('max', isNaN(itemdata('max')) ? options.max : itemdata('max'));
itemdata('step', itemdata('step') || options.step);
itemdata('readonly', itemdata('readonly') !== undefined ? itemdata('readonly') : options.readonly);
itemdata('resetable', itemdata('resetable') !== undefined ? itemdata('resetable') : options.resetable);
itemdata('backingfld', itemdata('backingfld') || options.backingfld);
itemdata('starwidth', itemdata('starwidth') || options.starwidth);
itemdata('starheight', itemdata('starheight') || options.starheight);
itemdata('value', Math.max(itemdata('min'), Math.min(itemdata('max'), (!isNaN(itemdata('value')) ? itemdata('value') : (!isNaN(options.value) ? options.value : options.min)))));
itemdata('ispreset', itemdata('ispreset') !== undefined ? itemdata('ispreset') : options.ispreset);
//are we LTR or RTL?
if (itemdata('backingfld')) {
//if we have a backing field, hide it, override defaults if range or select.
var fld = $(itemdata('backingfld')).hide();
if (fld.attr('disabled') || fld.attr('readonly')) {
itemdata('readonly', true); //http://rateit.codeplex.com/discussions/362055 , if a backing field is disabled or readonly at instantiation, make rateit readonly.
}
if (fld[0].nodeName == 'INPUT') {
if (fld[0].type == 'range' || fld[0].type == 'text') { //in browsers not support the range type, it defaults to text
itemdata('min', parseInt(fld.attr('min')) || itemdata('min')); //if we would have done fld[0].min it wouldn't have worked in browsers not supporting the range type.
itemdata('max', parseInt(fld.attr('max')) || itemdata('max'));
itemdata('step', parseInt(fld.attr('step')) || itemdata('step'));
}
}
if (fld[0].nodeName == 'SELECT' && fld[0].options.length > 1) {
itemdata('min', (!isNaN(itemdata('min')) ? itemdata('min') : Number(fld[0].options[0].value)));
itemdata('max', Number(fld[0].options[fld[0].length - 1].value));
itemdata('step', Number(fld[0].options[1].value) - Number(fld[0].options[0].value));
//see if we have a option that as explicity been selected
var selectedOption = fld.find('option[selected]');
if (selectedOption.length == 1) {
itemdata('value', selectedOption.val());
}
}
else {
//if it is not a select box, we can get's it's value using the val function.
//If it is a selectbox, we always get a value (the first one of the list), even if it was not explicity set.
itemdata('value', fld.val());
}
}
//Create the necessary tags. For ARIA purposes we need to give the items an ID. So we use an internal index to create unique ids
var element = item[0].nodeName == 'DIV' ? 'div' : 'span';
index++;
var html = '<button id="rateit-reset-{{index}}" type="button" data-role="none" class="rateit-reset" aria-label="' + $.rateit.aria.resetLabel + '" aria-controls="rateit-range-{{index}}"></button><{{element}} id="rateit-range-{{index}}" class="rateit-range" tabindex="0" role="slider" aria-label="' + $.rateit.aria.ratingLabel + '" aria-owns="rateit-reset-{{index}}" aria-valuemin="' + itemdata('min') + '" aria-valuemax="' + itemdata('max') + '" aria-valuenow="' + itemdata('value') + '"><{{element}} class="rateit-selected" style="height:' + itemdata('starheight') + 'px"></{{element}}><{{element}} class="rateit-hover" style="height:' + itemdata('starheight') + 'px"></{{element}}></{{element}}>';
item.append(html.replace(/{{index}}/gi, index).replace(/{{element}}/gi, element));
//if we are in RTL mode, we have to change the float of the "reset button"
if (!ltr) {
item.find('.rateit-reset').css('float', 'right');
item.find('.rateit-selected').addClass('rateit-selected-rtl');
item.find('.rateit-hover').addClass('rateit-hover-rtl');
}
itemdata('init', JSON.parse(JSON.stringify(item.data()))); //cheap way to create a clone
}
//resize the height of all elements,
item.find('.rateit-selected, .rateit-hover').height(itemdata('starheight'));
//set the range element to fit all the stars.
var range = item.find('.rateit-range');
range.width(itemdata('starwidth') * (itemdata('max') - itemdata('min'))).height(itemdata('starheight'));
//add/remove the preset class
var presetclass = 'rateit-preset' + ((ltr) ? '' : '-rtl');
if (itemdata('ispreset')) {
item.find('.rateit-selected').addClass(presetclass);
}
else {
item.find('.rateit-selected').removeClass(presetclass);
}
//set the value if we have it.
if (itemdata('value') != null) {
var score = (itemdata('value') - itemdata('min')) * itemdata('starwidth');
item.find('.rateit-selected').width(score);
}
//setup the reset button
var resetbtn = item.find('.rateit-reset');
if (resetbtn.data('wired') !== true) {
resetbtn.bind('click', function (e) {
e.preventDefault();
resetbtn.blur();
var event = $.Event('beforereset');
item.trigger(event);
if (event.isDefaultPrevented()) {
return false;
}
item.rateit('value', null);
item.trigger('reset');
}).data('wired', true);
}
//this function calculates the score based on the current position of the mouse.
var calcRawScore = function (element, event) {
var pageX = (event.changedTouches) ? event.changedTouches[0].pageX : event.pageX;
var offsetx = pageX - $(element).offset().left;
if (!ltr) { offsetx = range.width() - offsetx };
if (offsetx > range.width()) { offsetx = range.width(); }
if (offsetx < 0) { offsetx = 0; }
return score = Math.ceil(offsetx / itemdata('starwidth') * (1 / itemdata('step')));
};
//sets the hover element based on the score.
var setHover = function (score) {
var w = score * itemdata('starwidth') * itemdata('step');
var h = range.find('.rateit-hover');
if (h.data('width') != w) {
range.find('.rateit-selected').hide();
h.width(w).show().data('width', w);
var data = [(score * itemdata('step')) + itemdata('min')];
item.trigger('hover', data).trigger('over', data);
}
};
var setSelection = function (value) {
var event = $.Event('beforerated');
item.trigger(event, [value]);
if (event.isDefaultPrevented()) {
return false;
}
itemdata('value', value);
if (itemdata('backingfld')) {
$(itemdata('backingfld')).val(value).trigger('change');
}
if (itemdata('ispreset')) { //if it was a preset value, unset that.
range.find('.rateit-selected').removeClass(presetclass);
itemdata('ispreset', false);
}
range.find('.rateit-hover').hide();
range.find('.rateit-selected').width(value * itemdata('starwidth') - (itemdata('min') * itemdata('starwidth'))).show();
item.trigger('hover', [null]).trigger('over', [null]).trigger('rated', [value]);
return true;
};
if (!itemdata('readonly')) {
//if we are not read only, add all the events
//if we have a reset button, set the event handler.
if (!itemdata('resetable')) {
resetbtn.hide();
}
//when the mouse goes over the range element, we set the "hover" stars.
if (!itemdata('wired')) {
range.bind('touchmove touchend', touchHandler); //bind touch events
range.mousemove(function (e) {
var score = calcRawScore(this, e);
setHover(score);
});
//when the mouse leaves the range, we have to hide the hover stars, and show the current value.
range.mouseleave(function (e) {
range.find('.rateit-hover').hide().width(0).data('width', '');
item.trigger('hover', [null]).trigger('over', [null]);
range.find('.rateit-selected').show();
});
//when we click on the range, we have to set the value, hide the hover.
range.mouseup(function (e) {
var score = calcRawScore(this, e);
var value = (score * itemdata('step')) + itemdata('min');
setSelection(value);
range.blur();
});
//support key nav
range.keyup(function (e) {
if (e.which == 38 || e.which == (ltr ? 39 : 37)) {
setSelection(Math.min(itemdata('value') + itemdata('step'), itemdata('max')));
}
if (e.which == 40 || e.which == (ltr ? 37 : 39)) {
setSelection(Math.max(itemdata('value') - itemdata('step'), itemdata('min')));
}
});
itemdata('wired', true);
}
if (itemdata('resetable')) {
resetbtn.show();
}
}
else {
resetbtn.hide();
}
range.attr('aria-readonly', itemdata('readonly'));
});
};
//touch converter http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript/
function touchHandler(event) {
var touches = event.originalEvent.changedTouches,
first = touches[0],
type = "";
switch (event.type) {
case "touchmove": type = "mousemove"; break;
case "touchend": type = "mouseup"; break;
default: return;
}
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1,
first.screenX, first.screenY,
first.clientX, first.clientY, false,
false, false, false, 0/*left*/, null);
first.target.dispatchEvent(simulatedEvent);
event.preventDefault();
};
//some default values.
$.fn.rateit.defaults = { min: 0, max: 5, step: 0.5, starwidth: 16, starheight: 16, readonly: false, resetable: true, ispreset: false };
//invoke it on all .rateit elements. This could be removed if not wanted.
$(function () { $('div.rateit, span.rateit').rateit(); });
})(jQuery);