jquery.raty.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. /*!
  2. * jQuery Raty - A Star Rating Plugin
  3. *
  4. * The MIT License
  5. *
  6. * author: Washington Botelho
  7. * github: wbotelhos/raty
  8. * version: 2.8.0
  9. *
  10. */
  11. (function($) {
  12. 'use strict';
  13. var methods = {
  14. init: function(options) {
  15. return this.each(function() {
  16. this.self = $(this);
  17. methods.destroy.call(this.self);
  18. this.opt = $.extend(true, {}, $.fn.raty.defaults, options, this.self.data());
  19. methods._adjustCallback.call(this);
  20. methods._adjustNumber.call(this);
  21. methods._adjustHints.call(this);
  22. this.opt.score = methods._adjustedScore.call(this, this.opt.score);
  23. if (this.opt.starType !== 'img') {
  24. methods._adjustStarType.call(this);
  25. }
  26. methods._adjustPath.call(this);
  27. methods._createStars.call(this);
  28. if (this.opt.cancel) {
  29. methods._createCancel.call(this);
  30. }
  31. if (this.opt.precision) {
  32. methods._adjustPrecision.call(this);
  33. }
  34. methods._createScore.call(this);
  35. methods._apply.call(this, this.opt.score);
  36. methods._setTitle.call(this, this.opt.score);
  37. methods._target.call(this, this.opt.score);
  38. if (this.opt.readOnly) {
  39. methods._lock.call(this);
  40. } else {
  41. this.style.cursor = 'pointer';
  42. methods._binds.call(this);
  43. }
  44. });
  45. },
  46. _adjustCallback: function() {
  47. var options = ['number', 'readOnly', 'score', 'scoreName', 'target', 'path'];
  48. for (var i = 0; i < options.length; i++) {
  49. if (typeof this.opt[options[i]] === 'function') {
  50. this.opt[options[i]] = this.opt[options[i]].call(this);
  51. }
  52. }
  53. },
  54. _adjustedScore: function(score) {
  55. if (!score) {
  56. return score;
  57. }
  58. return methods._between(score, 0, this.opt.number);
  59. },
  60. _adjustHints: function() {
  61. if (!this.opt.hints) {
  62. this.opt.hints = [];
  63. }
  64. if (!this.opt.halfShow && !this.opt.half) {
  65. return;
  66. }
  67. var steps = this.opt.precision ? 10 : 2;
  68. for (var i = 0; i < this.opt.number; i++) {
  69. var group = this.opt.hints[i];
  70. if (Object.prototype.toString.call(group) !== '[object Array]') {
  71. group = [group];
  72. }
  73. this.opt.hints[i] = [];
  74. for (var j = 0; j < steps; j++) {
  75. var
  76. hint = group[j],
  77. last = group[group.length - 1];
  78. if (last === undefined) {
  79. last = null;
  80. }
  81. this.opt.hints[i][j] = hint === undefined ? last : hint;
  82. }
  83. }
  84. },
  85. _adjustNumber: function() {
  86. this.opt.number = methods._between(this.opt.number, 1, this.opt.numberMax);
  87. },
  88. _adjustPath: function() {
  89. this.opt.path = this.opt.path || '';
  90. if (this.opt.path && this.opt.path.charAt(this.opt.path.length - 1) !== '/') {
  91. this.opt.path += '/';
  92. }
  93. },
  94. _adjustPrecision: function() {
  95. this.opt.half = true;
  96. },
  97. _adjustStarType: function() {
  98. var replaces = ['cancelOff', 'cancelOn', 'starHalf', 'starOff', 'starOn'];
  99. this.opt.path = '';
  100. for (var i = 0; i < replaces.length; i++) {
  101. this.opt[replaces[i]] = this.opt[replaces[i]].replace('.', '-');
  102. }
  103. },
  104. _apply: function(score) {
  105. methods._fill.call(this, score);
  106. if (score) {
  107. if (score > 0) {
  108. this.score.val(score);
  109. }
  110. methods._roundStars.call(this, score);
  111. }
  112. },
  113. _between: function(value, min, max) {
  114. return Math.min(Math.max(parseFloat(value), min), max);
  115. },
  116. _binds: function() {
  117. if (this.cancel) {
  118. methods._bindOverCancel.call(this);
  119. methods._bindClickCancel.call(this);
  120. methods._bindOutCancel.call(this);
  121. }
  122. methods._bindOver.call(this);
  123. methods._bindClick.call(this);
  124. methods._bindOut.call(this);
  125. },
  126. _bindClick: function() {
  127. var that = this;
  128. that.stars.on('click.raty', function(evt) {
  129. var
  130. execute = true,
  131. score = (that.opt.half || that.opt.precision) ? that.self.data('score') : (this.alt || $(this).data('alt'));
  132. if (that.opt.click) {
  133. execute = that.opt.click.call(that, +score, evt);
  134. }
  135. if (execute || execute === undefined) {
  136. if (that.opt.half && !that.opt.precision) {
  137. score = methods._roundHalfScore.call(that, score);
  138. }
  139. methods._apply.call(that, score);
  140. }
  141. });
  142. },
  143. _bindClickCancel: function() {
  144. var that = this;
  145. that.cancel.on('click.raty', function(evt) {
  146. that.score.removeAttr('value');
  147. if (that.opt.click) {
  148. that.opt.click.call(that, null, evt);
  149. }
  150. });
  151. },
  152. _bindOut: function() {
  153. var that = this;
  154. that.self.on('mouseleave.raty', function(evt) {
  155. var score = +that.score.val() || undefined;
  156. methods._apply.call(that, score);
  157. methods._target.call(that, score, evt);
  158. methods._resetTitle.call(that);
  159. if (that.opt.mouseout) {
  160. that.opt.mouseout.call(that, score, evt);
  161. }
  162. });
  163. },
  164. _bindOutCancel: function() {
  165. var that = this;
  166. that.cancel.on('mouseleave.raty', function(evt) {
  167. var icon = that.opt.cancelOff;
  168. if (that.opt.starType !== 'img') {
  169. icon = that.opt.cancelClass + ' ' + icon;
  170. }
  171. methods._setIcon.call(that, this, icon);
  172. if (that.opt.mouseout) {
  173. var score = +that.score.val() || undefined;
  174. that.opt.mouseout.call(that, score, evt);
  175. }
  176. });
  177. },
  178. _bindOver: function() {
  179. var
  180. that = this,
  181. action = that.opt.half ? 'mousemove.raty' : 'mouseover.raty';
  182. that.stars.on(action, function(evt) {
  183. var score = methods._getScoreByPosition.call(that, evt, this);
  184. methods._fill.call(that, score);
  185. if (that.opt.half) {
  186. methods._roundStars.call(that, score, evt);
  187. methods._setTitle.call(that, score, evt);
  188. that.self.data('score', score);
  189. }
  190. methods._target.call(that, score, evt);
  191. if (that.opt.mouseover) {
  192. that.opt.mouseover.call(that, score, evt);
  193. }
  194. });
  195. },
  196. _bindOverCancel: function() {
  197. var that = this;
  198. that.cancel.on('mouseover.raty', function(evt) {
  199. var
  200. starOff = that.opt.path + that.opt.starOff,
  201. icon = that.opt.cancelOn;
  202. if (that.opt.starType === 'img') {
  203. that.stars.attr('src', starOff);
  204. } else {
  205. icon = that.opt.cancelClass + ' ' + icon;
  206. that.stars.attr('class', starOff);
  207. }
  208. methods._setIcon.call(that, this, icon);
  209. methods._target.call(that, null, evt);
  210. if (that.opt.mouseover) {
  211. that.opt.mouseover.call(that, null);
  212. }
  213. });
  214. },
  215. _buildScoreField: function() {
  216. return $('<input />', { name: this.opt.scoreName, type: 'hidden' }).appendTo(this);
  217. },
  218. _createCancel: function() {
  219. var
  220. icon = this.opt.path + this.opt.cancelOff,
  221. cancel = $('<' + this.opt.starType + ' />', { title: this.opt.cancelHint, 'class': this.opt.cancelClass });
  222. if (this.opt.starType === 'img') {
  223. cancel.attr({ src: icon, alt: 'x' });
  224. } else {
  225. // TODO: use $.data
  226. cancel.attr('data-alt', 'x').addClass(icon);
  227. }
  228. if (this.opt.cancelPlace === 'left') {
  229. this.self.prepend('&#160;').prepend(cancel);
  230. } else {
  231. this.self.append('&#160;').append(cancel);
  232. }
  233. this.cancel = cancel;
  234. },
  235. _createScore: function() {
  236. var score = $(this.opt.targetScore);
  237. this.score = score.length ? score : methods._buildScoreField.call(this);
  238. },
  239. _createStars: function() {
  240. for (var i = 1; i <= this.opt.number; i++) {
  241. var
  242. name = methods._nameForIndex.call(this, i),
  243. attrs = { alt: i, src: this.opt.path + this.opt[name] };
  244. if (this.opt.starType !== 'img') {
  245. attrs = { 'data-alt': i, 'class': attrs.src }; // TODO: use $.data.
  246. }
  247. attrs.title = methods._getHint.call(this, i);
  248. $('<' + this.opt.starType + ' />', attrs).appendTo(this);
  249. if (this.opt.space) {
  250. this.self.append(i < this.opt.number ? '&#160;' : '');
  251. }
  252. }
  253. this.stars = this.self.children(this.opt.starType);
  254. },
  255. _error: function(message) {
  256. $(this).text(message);
  257. $.error(message);
  258. },
  259. _fill: function(score) {
  260. var hash = 0;
  261. for (var i = 1; i <= this.stars.length; i++) {
  262. var
  263. icon,
  264. star = this.stars[i - 1],
  265. turnOn = methods._turnOn.call(this, i, score);
  266. if (this.opt.iconRange && this.opt.iconRange.length > hash) {
  267. var irange = this.opt.iconRange[hash];
  268. icon = methods._getRangeIcon.call(this, irange, turnOn);
  269. if (i <= irange.range) {
  270. methods._setIcon.call(this, star, icon);
  271. }
  272. if (i === irange.range) {
  273. hash++;
  274. }
  275. } else {
  276. icon = this.opt[turnOn ? 'starOn' : 'starOff'];
  277. methods._setIcon.call(this, star, icon);
  278. }
  279. }
  280. },
  281. _getFirstDecimal: function(number) {
  282. var
  283. decimal = number.toString().split('.')[1],
  284. result = 0;
  285. if (decimal) {
  286. result = parseInt(decimal.charAt(0), 10);
  287. if (decimal.slice(1, 5) === '9999') {
  288. result++;
  289. }
  290. }
  291. return result;
  292. },
  293. _getRangeIcon: function(irange, turnOn) {
  294. return turnOn ? irange.on || this.opt.starOn : irange.off || this.opt.starOff;
  295. },
  296. _getScoreByPosition: function(evt, icon) {
  297. var score = parseInt(icon.alt || icon.getAttribute('data-alt'), 10);
  298. if (this.opt.half) {
  299. var
  300. size = methods._getWidth.call(this),
  301. percent = parseFloat((evt.pageX - $(icon).offset().left) / size);
  302. score = score - 1 + percent;
  303. }
  304. return score;
  305. },
  306. _getHint: function(score, evt) {
  307. if (score !== 0 && !score) {
  308. return this.opt.noRatedMsg;
  309. }
  310. var
  311. decimal = methods._getFirstDecimal.call(this, score),
  312. integer = Math.ceil(score),
  313. group = this.opt.hints[(integer || 1) - 1],
  314. hint = group,
  315. set = !evt || this.move;
  316. if (this.opt.precision) {
  317. if (set) {
  318. decimal = decimal === 0 ? 9 : decimal - 1;
  319. }
  320. hint = group[decimal];
  321. } else if (this.opt.halfShow || this.opt.half) {
  322. decimal = set && decimal === 0 ? 1 : decimal > 5 ? 1 : 0;
  323. hint = group[decimal];
  324. }
  325. return hint === '' ? '' : hint || score;
  326. },
  327. _getWidth: function() {
  328. var width = this.stars[0].width || parseFloat(this.stars.eq(0).css('font-size'));
  329. if (!width) {
  330. methods._error.call(this, 'Could not get the icon width!');
  331. }
  332. return width;
  333. },
  334. _lock: function() {
  335. var hint = methods._getHint.call(this, this.score.val());
  336. this.style.cursor = '';
  337. this.title = hint;
  338. this.score.prop('readonly', true);
  339. this.stars.prop('title', hint);
  340. if (this.cancel) {
  341. this.cancel.hide();
  342. }
  343. this.self.data('readonly', true);
  344. },
  345. _nameForIndex: function(i) {
  346. return this.opt.score && this.opt.score >= i ? 'starOn' : 'starOff';
  347. },
  348. _resetTitle: function() {
  349. for (var i = 0; i < this.opt.number; i++) {
  350. this.stars[i].title = methods._getHint.call(this, i + 1);
  351. }
  352. },
  353. _roundHalfScore: function(score) {
  354. var
  355. integer = parseInt(score, 10),
  356. decimal = methods._getFirstDecimal.call(this, score);
  357. if (decimal !== 0) {
  358. decimal = decimal > 5 ? 1 : 0.5;
  359. }
  360. return integer + decimal;
  361. },
  362. _roundStars: function(score, evt) {
  363. var
  364. decimal = (score % 1).toFixed(2),
  365. name ;
  366. if (evt || this.move) {
  367. name = decimal > 0.5 ? 'starOn' : 'starHalf';
  368. } else if (decimal > this.opt.round.down) { // Up: [x.76 .. x.99]
  369. name = 'starOn';
  370. if (this.opt.halfShow && decimal < this.opt.round.up) { // Half: [x.26 .. x.75]
  371. name = 'starHalf';
  372. } else if (decimal < this.opt.round.full) { // Down: [x.00 .. x.5]
  373. name = 'starOff';
  374. }
  375. }
  376. if (name) {
  377. var
  378. icon = this.opt[name],
  379. star = this.stars[Math.ceil(score) - 1];
  380. methods._setIcon.call(this, star, icon);
  381. } // Full down: [x.00 .. x.25]
  382. },
  383. _setIcon: function(star, icon) {
  384. star[this.opt.starType === 'img' ? 'src' : 'className'] = this.opt.path + icon;
  385. },
  386. _setTarget: function(target, score) {
  387. if (score) {
  388. score = this.opt.targetFormat.toString().replace('{score}', score);
  389. }
  390. if (target.is(':input')) {
  391. target.val(score);
  392. } else {
  393. target.html(score);
  394. }
  395. },
  396. _setTitle: function(score, evt) {
  397. if (score) {
  398. var
  399. integer = parseInt(Math.ceil(score), 10),
  400. star = this.stars[integer - 1];
  401. star.title = methods._getHint.call(this, score, evt);
  402. }
  403. },
  404. _target: function(score, evt) {
  405. if (this.opt.target) {
  406. var target = $(this.opt.target);
  407. if (!target.length) {
  408. methods._error.call(this, 'Target selector invalid or missing!');
  409. }
  410. var mouseover = evt && evt.type === 'mouseover';
  411. if (score === undefined) {
  412. score = this.opt.targetText;
  413. } else if (score === null) {
  414. score = mouseover ? this.opt.cancelHint : this.opt.targetText;
  415. } else {
  416. if (this.opt.targetType === 'hint') {
  417. score = methods._getHint.call(this, score, evt);
  418. } else if (this.opt.precision) {
  419. score = parseFloat(score).toFixed(1);
  420. }
  421. var mousemove = evt && evt.type === 'mousemove';
  422. if (!mouseover && !mousemove && !this.opt.targetKeep) {
  423. score = this.opt.targetText;
  424. }
  425. }
  426. methods._setTarget.call(this, target, score);
  427. }
  428. },
  429. _turnOn: function(i, score) {
  430. return this.opt.single ? (i === score) : (i <= score);
  431. },
  432. _unlock: function() {
  433. this.style.cursor = 'pointer';
  434. this.removeAttribute('title');
  435. this.score.removeAttr('readonly');
  436. this.self.data('readonly', false);
  437. for (var i = 0; i < this.opt.number; i++) {
  438. this.stars[i].title = methods._getHint.call(this, i + 1);
  439. }
  440. if (this.cancel) {
  441. this.cancel.css('display', '');
  442. }
  443. },
  444. cancel: function(click) {
  445. return this.each(function() {
  446. var self = $(this);
  447. if (self.data('readonly') !== true) {
  448. methods[click ? 'click' : 'score'].call(self, null);
  449. this.score.removeAttr('value');
  450. }
  451. });
  452. },
  453. click: function(score) {
  454. return this.each(function() {
  455. if ($(this).data('readonly') !== true) {
  456. score = methods._adjustedScore.call(this, score);
  457. methods._apply.call(this, score);
  458. if (this.opt.click) {
  459. this.opt.click.call(this, score, $.Event('click'));
  460. }
  461. methods._target.call(this, score);
  462. }
  463. });
  464. },
  465. destroy: function() {
  466. return this.each(function() {
  467. var
  468. self = $(this),
  469. raw = self.data('raw');
  470. if (raw) {
  471. self.off('.raty').empty().css({ cursor: raw.style.cursor }).removeData('readonly');
  472. } else {
  473. self.data('raw', self.clone()[0]);
  474. }
  475. });
  476. },
  477. getScore: function() {
  478. var
  479. score = [],
  480. value ;
  481. this.each(function() {
  482. value = this.score.val();
  483. score.push(value ? +value : undefined);
  484. });
  485. return (score.length > 1) ? score : score[0];
  486. },
  487. move: function(score) {
  488. return this.each(function() {
  489. var
  490. integer = parseInt(score, 10),
  491. decimal = methods._getFirstDecimal.call(this, score);
  492. if (integer >= this.opt.number) {
  493. integer = this.opt.number - 1;
  494. decimal = 10;
  495. }
  496. var
  497. width = methods._getWidth.call(this),
  498. steps = width / 10,
  499. star = $(this.stars[integer]),
  500. percent = star.offset().left + steps * decimal,
  501. evt = $.Event('mousemove', { pageX: percent });
  502. this.move = true;
  503. star.trigger(evt);
  504. this.move = false;
  505. });
  506. },
  507. readOnly: function(readonly) {
  508. return this.each(function() {
  509. var self = $(this);
  510. if (self.data('readonly') !== readonly) {
  511. if (readonly) {
  512. self.off('.raty').children(this.opt.starType).off('.raty');
  513. methods._lock.call(this);
  514. } else {
  515. methods._binds.call(this);
  516. methods._unlock.call(this);
  517. }
  518. self.data('readonly', readonly);
  519. }
  520. });
  521. },
  522. reload: function() {
  523. return methods.set.call(this, {});
  524. },
  525. score: function() {
  526. var self = $(this);
  527. return arguments.length ? methods.setScore.apply(self, arguments) : methods.getScore.call(self);
  528. },
  529. set: function(options) {
  530. return this.each(function() {
  531. $(this).raty($.extend({}, this.opt, options));
  532. });
  533. },
  534. setScore: function(score) {
  535. return this.each(function() {
  536. if ($(this).data('readonly') !== true) {
  537. score = methods._adjustedScore.call(this, score);
  538. methods._apply.call(this, score);
  539. methods._target.call(this, score);
  540. }
  541. });
  542. }
  543. };
  544. $.fn.raty = function(method) {
  545. if (methods[method]) {
  546. return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
  547. } else if (typeof method === 'object' || !method) {
  548. return methods.init.apply(this, arguments);
  549. } else {
  550. $.error('Method ' + method + ' does not exist!');
  551. }
  552. };
  553. $.fn.raty.defaults = {
  554. cancel: false,
  555. cancelClass: 'raty-cancel',
  556. cancelHint: 'Cancel this rating!',
  557. cancelOff: 'cancel-off.png',
  558. cancelOn: 'cancel-on.png',
  559. cancelPlace: 'left',
  560. click: undefined,
  561. half: false,
  562. halfShow: true,
  563. hints: ['bad', 'poor', 'regular', 'good', 'gorgeous'],
  564. iconRange: undefined,
  565. mouseout: undefined,
  566. mouseover: undefined,
  567. noRatedMsg: 'Not rated yet!',
  568. number: 5,
  569. numberMax: 20,
  570. path: undefined,
  571. precision: false,
  572. readOnly: false,
  573. round: { down: 0.25, full: 0.6, up: 0.76 },
  574. score: undefined,
  575. scoreName: 'score',
  576. single: false,
  577. space: true,
  578. starHalf: 'star-half.png',
  579. starOff: 'star-off.png',
  580. starOn: 'star-on.png',
  581. starType: 'img',
  582. target: undefined,
  583. targetFormat: '{score}',
  584. targetKeep: false,
  585. targetScore: undefined,
  586. targetText: '',
  587. targetType: 'hint'
  588. };
  589. })(jQuery);