jquery.raty.js 19 KB

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