jquery.raty.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. /*!
  2. * jQuery Raty - A Star Rating Plugin
  3. * ------------------------------------------------------------------
  4. *
  5. * jQuery Raty is a plugin that generates a customizable star rating.
  6. *
  7. * Licensed under The MIT License
  8. *
  9. * @version 2.5.2
  10. * @since 2010.06.11
  11. * @author Washington Botelho
  12. * @documentation wbotelhos.com/raty
  13. *
  14. * ------------------------------------------------------------------
  15. *
  16. * <div id="star"></div>
  17. *
  18. * $('#star').raty();
  19. *
  20. */
  21. ;(function($) {
  22. var methods = {
  23. init: function(settings) {
  24. return this.each(function() {
  25. methods.destroy.call(this);
  26. this.opt = $.extend(true, {}, $.fn.raty.defaults, settings);
  27. var that = $(this),
  28. inits = ['number', 'readOnly', 'score', 'scoreName'];
  29. methods._callback.call(this, inits);
  30. if (this.opt.precision) {
  31. methods._adjustPrecision.call(this);
  32. }
  33. this.opt.number = methods._between(this.opt.number, 0, this.opt.numberMax)
  34. this.opt.path = this.opt.path || '';
  35. if (this.opt.path && this.opt.path.slice(this.opt.path.length - 1, this.opt.path.length) !== '/') {
  36. this.opt.path += '/';
  37. }
  38. this.stars = methods._createStars.call(this);
  39. this.score = methods._createScore.call(this);
  40. methods._apply.call(this, this.opt.score);
  41. var space = this.opt.space ? 4 : 0,
  42. width = this.opt.width || (this.opt.number * this.opt.size + this.opt.number * space);
  43. if (this.opt.cancel) {
  44. this.cancel = methods._createCancel.call(this);
  45. width += (this.opt.size + space);
  46. }
  47. if (this.opt.readOnly) {
  48. methods._lock.call(this);
  49. } else {
  50. that.css('cursor', 'pointer');
  51. methods._binds.call(this);
  52. }
  53. if (this.opt.width !== false) {
  54. that.css('width', width);
  55. }
  56. methods._target.call(this, this.opt.score);
  57. that.data({ 'settings': this.opt, 'raty': true });
  58. });
  59. }, _adjustPrecision: function() {
  60. this.opt.targetType = 'score';
  61. this.opt.half = true;
  62. }, _apply: function(score) {
  63. if (score && score > 0) {
  64. score = methods._between(score, 0, this.opt.number);
  65. this.score.val(score);
  66. }
  67. methods._fill.call(this, score);
  68. if (score) {
  69. methods._roundStars.call(this, score);
  70. }
  71. }, _between: function(value, min, max) {
  72. return Math.min(Math.max(parseFloat(value), min), max);
  73. }, _binds: function() {
  74. if (this.cancel) {
  75. methods._bindCancel.call(this);
  76. }
  77. methods._bindClick.call(this);
  78. methods._bindOut.call(this);
  79. methods._bindOver.call(this);
  80. }, _bindCancel: function() {
  81. methods._bindClickCancel.call(this);
  82. methods._bindOutCancel.call(this);
  83. methods._bindOverCancel.call(this);
  84. }, _bindClick: function() {
  85. var self = this,
  86. that = $(self);
  87. self.stars.on('click.raty', function(evt) {
  88. self.score.val((self.opt.half || self.opt.precision) ? that.data('score') : this.alt);
  89. if (self.opt.click) {
  90. self.opt.click.call(self, parseFloat(self.score.val()), evt);
  91. }
  92. });
  93. }, _bindClickCancel: function() {
  94. var self = this;
  95. self.cancel.on('click.raty', function(evt) {
  96. self.score.removeAttr('value');
  97. if (self.opt.click) {
  98. self.opt.click.call(self, null, evt);
  99. }
  100. });
  101. }, _bindOut: function() {
  102. var self = this;
  103. $(this).on('mouseleave.raty', function(evt) {
  104. var score = parseFloat(self.score.val()) || undefined;
  105. methods._apply.call(self, score);
  106. methods._target.call(self, score, evt);
  107. if (self.opt.mouseout) {
  108. self.opt.mouseout.call(self, score, evt);
  109. }
  110. });
  111. }, _bindOutCancel: function() {
  112. var self = this;
  113. self.cancel.on('mouseleave.raty', function(evt) {
  114. $(this).attr('src', self.opt.path + self.opt.cancelOff);
  115. if (self.opt.mouseout) {
  116. self.opt.mouseout.call(self, self.score.val() || null, evt);
  117. }
  118. });
  119. }, _bindOverCancel: function() {
  120. var self = this;
  121. self.cancel.on('mouseover.raty', function(evt) {
  122. $(this).attr('src', self.opt.path + self.opt.cancelOn);
  123. self.stars.attr('src', self.opt.path + self.opt.starOff);
  124. methods._target.call(self, null, evt);
  125. if (self.opt.mouseover) {
  126. self.opt.mouseover.call(self, null);
  127. }
  128. });
  129. }, _bindOver: function() {
  130. var self = this,
  131. that = $(self),
  132. action = self.opt.half ? 'mousemove.raty' : 'mouseover.raty';
  133. self.stars.on(action, function(evt) {
  134. var score = parseInt(this.alt, 10);
  135. if (self.opt.half) {
  136. var position = parseFloat((evt.pageX - $(this).offset().left) / self.opt.size),
  137. plus = (position > .5) ? 1 : .5;
  138. score = score - 1 + plus;
  139. methods._fill.call(self, score);
  140. if (self.opt.precision) {
  141. score = score - plus + position;
  142. }
  143. methods._roundStars.call(self, score);
  144. that.data('score', score);
  145. } else {
  146. methods._fill.call(self, score);
  147. }
  148. methods._target.call(self, score, evt);
  149. if (self.opt.mouseover) {
  150. self.opt.mouseover.call(self, score, evt);
  151. }
  152. });
  153. }, _callback: function(options) {
  154. for (i in options) {
  155. if (typeof this.opt[options[i]] === 'function') {
  156. this.opt[options[i]] = this.opt[options[i]].call(this);
  157. }
  158. }
  159. }, _createCancel: function() {
  160. var that = $(this),
  161. icon = this.opt.path + this.opt.cancelOff,
  162. cancel = $('<img />', { src: icon, alt: 'x', title: this.opt.cancelHint, 'class': 'raty-cancel' });
  163. if (this.opt.cancelPlace == 'left') {
  164. that.prepend('&#160;').prepend(cancel);
  165. } else {
  166. that.append('&#160;').append(cancel);
  167. }
  168. return cancel;
  169. }, _createScore: function() {
  170. return $('<input />', { type: 'hidden', name: this.opt.scoreName }).appendTo(this);
  171. }, _createStars: function() {
  172. var that = $(this);
  173. for (var i = 1; i <= this.opt.number; i++) {
  174. var title = methods._getHint.call(this, i),
  175. icon = (this.opt.score && this.opt.score >= i) ? 'starOn' : 'starOff';
  176. icon = this.opt.path + this.opt[icon];
  177. $('<img />', { src : icon, alt: i, title: title }).appendTo(this);
  178. if (this.opt.space) {
  179. that.append((i < this.opt.number) ? '&#160;' : '');
  180. }
  181. }
  182. return that.children('img');
  183. }, _error: function(message) {
  184. $(this).html(message);
  185. $.error(message);
  186. }, _fill: function(score) {
  187. var self = this,
  188. hash = 0;
  189. for (var i = 1; i <= self.stars.length; i++) {
  190. var star = self.stars.eq(i - 1),
  191. select = self.opt.single ? (i == score) : (i <= score);
  192. if (self.opt.iconRange && self.opt.iconRange.length > hash) {
  193. var irange = self.opt.iconRange[hash],
  194. on = irange.on || self.opt.starOn,
  195. off = irange.off || self.opt.starOff,
  196. icon = select ? on : off;
  197. if (i <= irange.range) {
  198. star.attr('src', self.opt.path + icon);
  199. }
  200. if (i == irange.range) {
  201. hash++;
  202. }
  203. } else {
  204. var icon = select ? 'starOn' : 'starOff';
  205. star.attr('src', this.opt.path + this.opt[icon]);
  206. }
  207. }
  208. }, _getHint: function(score) {
  209. var hint = this.opt.hints[score - 1];
  210. return (hint === '') ? '' : (hint || score);
  211. }, _lock: function() {
  212. var score = parseInt(this.score.val(), 10), // TODO: 3.1 >> [['1'], ['2'], ['3', '.1', '.2']]
  213. hint = score ? methods._getHint.call(this, score) : this.opt.noRatedMsg;
  214. $(this).data('readonly', true).css('cursor', '').attr('title', hint);
  215. this.score.attr('readonly', 'readonly');
  216. this.stars.attr('title', hint);
  217. if (this.cancel) {
  218. this.cancel.hide();
  219. }
  220. }, _roundStars: function(score) {
  221. var rest = (score - Math.floor(score)).toFixed(2);
  222. if (rest > this.opt.round.down) {
  223. var icon = 'starOn'; // Up: [x.76 .. x.99]
  224. if (this.opt.halfShow && rest < this.opt.round.up) { // Half: [x.26 .. x.75]
  225. icon = 'starHalf';
  226. } else if (rest < this.opt.round.full) { // Down: [x.00 .. x.5]
  227. icon = 'starOff';
  228. }
  229. this.stars.eq(Math.ceil(score) - 1).attr('src', this.opt.path + this.opt[icon]);
  230. } // Full down: [x.00 .. x.25]
  231. }, _target: function(score, evt) {
  232. if (this.opt.target) {
  233. var target = $(this.opt.target);
  234. if (target.length === 0) {
  235. methods._error.call(this, 'Target selector invalid or missing!');
  236. }
  237. if (this.opt.targetFormat.indexOf('{score}') < 0) {
  238. methods._error.call(this, 'Template "{score}" missing!');
  239. }
  240. var mouseover = evt && evt.type == 'mouseover';
  241. if (score === undefined) {
  242. score = this.opt.targetText;
  243. } else if (score === null) {
  244. score = mouseover ? this.opt.cancelHint : this.opt.targetText;
  245. } else {
  246. if (this.opt.targetType == 'hint') {
  247. score = methods._getHint.call(this, Math.ceil(score));
  248. } else if (this.opt.precision) {
  249. score = parseFloat(score).toFixed(1);
  250. }
  251. if (!mouseover && !this.opt.targetKeep) {
  252. score = this.opt.targetText;
  253. }
  254. }
  255. if (score) {
  256. score = this.opt.targetFormat.toString().replace('{score}', score);
  257. }
  258. if (target.is(':input')) {
  259. target.val(score);
  260. } else {
  261. target.html(score);
  262. }
  263. }
  264. }, _unlock: function() {
  265. $(this).data('readonly', false).css('cursor', 'pointer').removeAttr('title');
  266. this.score.removeAttr('readonly', 'readonly');
  267. for (var i = 0; i < this.opt.number; i++) {
  268. this.stars.eq(i).attr('title', methods._getHint.call(this, i + 1));
  269. }
  270. if (this.cancel) {
  271. this.cancel.css('display', '');
  272. }
  273. }, cancel: function(click) {
  274. return this.each(function() {
  275. if ($(this).data('readonly') !== true) {
  276. methods[click ? 'click' : 'score'].call(this, null);
  277. this.score.removeAttr('value');
  278. }
  279. });
  280. }, click: function(score) {
  281. return $(this).each(function() {
  282. if ($(this).data('readonly') !== true) {
  283. methods._apply.call(this, score);
  284. if (!this.opt.click) {
  285. methods._error.call(this, 'You must add the "click: function(score, evt) { }" callback.');
  286. }
  287. this.opt.click.call(this, score, { type: 'click' });
  288. methods._target.call(this, score);
  289. }
  290. });
  291. }, destroy: function() {
  292. return $(this).each(function() {
  293. var that = $(this),
  294. raw = that.data('raw');
  295. if (raw) {
  296. that.off('.raty').empty().css({ cursor: raw.style.cursor, width: raw.style.width }).removeData('readonly');
  297. } else {
  298. that.data('raw', that.clone()[0]);
  299. }
  300. });
  301. }, getScore: function() {
  302. var score = [],
  303. value ;
  304. $(this).each(function() {
  305. value = this.score.val();
  306. score.push(value ? parseFloat(value) : undefined);
  307. });
  308. return (score.length > 1) ? score : score[0];
  309. }, readOnly: function(readonly) {
  310. return this.each(function() {
  311. var that = $(this);
  312. if (that.data('readonly') !== readonly) {
  313. if (readonly) {
  314. that.off('.raty').children('img').off('.raty');
  315. methods._lock.call(this);
  316. } else {
  317. methods._binds.call(this);
  318. methods._unlock.call(this);
  319. }
  320. that.data('readonly', readonly);
  321. }
  322. });
  323. }, reload: function() {
  324. return methods.set.call(this, {});
  325. }, score: function() {
  326. return arguments.length ? methods.setScore.apply(this, arguments) : methods.getScore.call(this);
  327. }, set: function(settings) {
  328. return this.each(function() {
  329. var that = $(this),
  330. actual = that.data('settings'),
  331. news = $.extend({}, actual, settings);
  332. that.raty(news);
  333. });
  334. }, setScore: function(score) {
  335. return $(this).each(function() {
  336. if ($(this).data('readonly') !== true) {
  337. methods._apply.call(this, score);
  338. methods._target.call(this, score);
  339. }
  340. });
  341. }
  342. };
  343. $.fn.raty = function(method) {
  344. if (methods[method]) {
  345. return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
  346. } else if (typeof method === 'object' || !method) {
  347. return methods.init.apply(this, arguments);
  348. } else {
  349. $.error('Method ' + method + ' does not exist!');
  350. }
  351. };
  352. $.fn.raty.defaults = {
  353. cancel : false,
  354. cancelHint : 'Cancel this rating!',
  355. cancelOff : 'cancel-off.png',
  356. cancelOn : 'cancel-on.png',
  357. cancelPlace : 'left',
  358. click : undefined,
  359. half : false,
  360. halfShow : true,
  361. hints : ['bad', 'poor', 'regular', 'good', 'gorgeous'],
  362. iconRange : undefined,
  363. mouseout : undefined,
  364. mouseover : undefined,
  365. noRatedMsg : 'Not rated yet!',
  366. number : 5,
  367. numberMax : 20,
  368. path : '',
  369. precision : false,
  370. readOnly : false,
  371. round : { down: .25, full: .6, up: .76 },
  372. score : undefined,
  373. scoreName : 'score',
  374. single : false,
  375. size : 16,
  376. space : true,
  377. starHalf : 'star-half.png',
  378. starOff : 'star-off.png',
  379. starOn : 'star-on.png',
  380. target : undefined,
  381. targetFormat : '{score}',
  382. targetKeep : false,
  383. targetText : '',
  384. targetType : 'hint',
  385. width : undefined
  386. };
  387. })(jQuery);