jquery.star-rating.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /*
  2. * jQuery StarRatingSvg v1.2.0
  3. *
  4. * http://github.com/nashio/star-rating-svg
  5. * Author: Ignacio Chavez
  6. * hello@ignaciochavez.com
  7. * Licensed under MIT
  8. */
  9. ;(function ( $, window, document, undefined ) {
  10. 'use strict';
  11. // Create the defaults once
  12. var pluginName = 'starRating';
  13. var noop = function(){};
  14. var defaults = {
  15. totalStars: 5,
  16. useFullStars: false,
  17. starShape: 'straight',
  18. emptyColor: 'lightgray',
  19. hoverColor: '#f1c40f',
  20. activeColor: '#f1c40f',
  21. ratedColor: '#f1c40f',
  22. useGradient: true,
  23. readOnly: false,
  24. disableAfterRate: true,
  25. baseUrl: false,
  26. starGradient: {
  27. start: '#FEF7CD',
  28. end: '#FF9511'
  29. },
  30. strokeWidth: 4,
  31. strokeColor: 'black',
  32. initialRating: 0,
  33. starSize: 40,
  34. callback: noop,
  35. onHover: noop,
  36. onLeave: noop
  37. };
  38. // The actual plugin constructor
  39. var Plugin = function( element, options ) {
  40. var _rating;
  41. var newRating;
  42. var roundFn;
  43. this.element = element;
  44. this.$el = $(element);
  45. this.settings = $.extend( {}, defaults, options );
  46. // grab rating if defined on the element
  47. _rating = this.$el.data('rating') || this.settings.initialRating;
  48. // round to the nearest half
  49. roundFn = this.settings.forceRoundUp ? Math.ceil : Math.round;
  50. newRating = (roundFn( _rating * 2 ) / 2).toFixed(1);
  51. this._state = {
  52. rating: newRating
  53. };
  54. // create unique id for stars
  55. this._uid = Math.floor( Math.random() * 999 );
  56. // override gradient if not used
  57. if( !options.starGradient && !this.settings.useGradient ){
  58. this.settings.starGradient.start = this.settings.starGradient.end = this.settings.activeColor;
  59. }
  60. this._defaults = defaults;
  61. this._name = pluginName;
  62. this.init();
  63. };
  64. var methods = {
  65. init: function () {
  66. this.renderMarkup();
  67. this.addListeners();
  68. this.initRating();
  69. },
  70. addListeners: function(){
  71. if( this.settings.readOnly ){ return; }
  72. this.$stars.on('mouseover', this.hoverRating.bind(this));
  73. this.$stars.on('mouseout', this.restoreState.bind(this));
  74. this.$stars.on('click', this.handleRating.bind(this));
  75. },
  76. // apply styles to hovered stars
  77. hoverRating: function(e){
  78. var index = this.getIndex(e);
  79. this.paintStars(index, 'hovered');
  80. this.settings.onHover(index + 1, this._state.rating, this.$el);
  81. },
  82. // clicked on a rate, apply style and state
  83. handleRating: function(e){
  84. var index = this.getIndex(e);
  85. var rating = index + 1;
  86. this.applyRating(rating, this.$el);
  87. this.executeCallback( rating, this.$el );
  88. if(this.settings.disableAfterRate){
  89. this.$stars.off();
  90. }
  91. },
  92. applyRating: function(rating){
  93. var index = rating - 1;
  94. // paint selected and remove hovered color
  95. this.paintStars(index, 'rated');
  96. this._state.rating = index + 1;
  97. this._state.rated = true;
  98. },
  99. restoreState: function(e){
  100. var index = this.getIndex(e);
  101. var rating = this._state.rating || -1;
  102. // determine star color depending on manually rated
  103. var colorType = this._state.rated ? 'rated' : 'active';
  104. this.paintStars(rating - 1, colorType);
  105. this.settings.onLeave(index + 1, this._state.rating, this.$el);
  106. },
  107. getIndex: function(e){
  108. var $target = $(e.currentTarget);
  109. var width = $target.width();
  110. var side = $(e.target).attr('data-side');
  111. var minRating = this.settings.minRating;
  112. // hovered outside the star, calculate by pixel instead
  113. side = (!side) ? this.getOffsetByPixel(e, $target, width) : side;
  114. side = (this.settings.useFullStars) ? 'right' : side ;
  115. // get index for half or whole star
  116. var index = $target.index() - ((side === 'left') ? 0.5 : 0);
  117. // pointer is way to the left, rating should be none
  118. index = ( index < 0.5 && (e.offsetX < width / 4) ) ? -1 : index;
  119. // force minimum rating
  120. index = ( minRating && minRating <= this.settings.totalStars && index < minRating ) ? minRating - 1 : index;
  121. return index;
  122. },
  123. getOffsetByPixel: function(e, $target, width){
  124. var leftX = e.pageX - $target.offset().left;
  125. return ( leftX <= (width / 2) && !this.settings.useFullStars) ? 'left' : 'right';
  126. },
  127. initRating: function(){
  128. this.paintStars(this._state.rating - 1, 'active');
  129. },
  130. paintStars: function(endIndex, stateClass){
  131. var $polygonLeft;
  132. var $polygonRight;
  133. var leftClass;
  134. var rightClass;
  135. var s = this.settings;
  136. $.each(this.$stars, function(index, star){
  137. $polygonLeft = $(star).find('[data-side="left"]');
  138. $polygonRight = $(star).find('[data-side="right"]');
  139. leftClass = rightClass = (index <= endIndex) ? stateClass : 'empty';
  140. // has another half rating, add half star
  141. leftClass = ( index - endIndex === 0.5 ) ? stateClass : leftClass;
  142. $polygonLeft.attr('class', 'svg-' + leftClass + '-' + this._uid);
  143. $polygonRight.attr('class', 'svg-' + rightClass + '-' + this._uid);
  144. // get color for level
  145. var ratedColorsIndex = endIndex >= 0 ? Math.ceil(endIndex) : 0;
  146. var ratedColor;
  147. if (s.ratedColors && s.ratedColors.length && s.ratedColors[ratedColorsIndex]) {
  148. ratedColor = s.ratedColors[ratedColorsIndex];
  149. } else {
  150. ratedColor = this._defaults.ratedColor;
  151. }
  152. // only override colors in rated stars and when rated number is valid
  153. if (stateClass === 'rated' && endIndex > -1) {
  154. // limit to painting only to rated stars, and specific case for half star
  155. if (index <= Math.ceil(endIndex) || (index < 1 && endIndex < 0)) {
  156. $polygonLeft.attr('style', 'fill:'+ratedColor);
  157. }
  158. if (index <= endIndex) {
  159. $polygonRight.attr('style', 'fill:'+ratedColor);
  160. }
  161. }
  162. }.bind(this));
  163. },
  164. renderMarkup: function () {
  165. var s = this.settings;
  166. var baseUrl = s.baseUrl ? location.href.split('#')[0] : '';
  167. // inject an svg manually to have control over attributes
  168. var star = '<div class="jq-star" style="width:' + s.starSize+ 'px; height:' + s.starSize + 'px;"><svg version="1.0" class="jq-star-svg" shape-rendering="geometricPrecision" xmlns="http://www.w3.org/2000/svg" ' + this.getSvgDimensions(s.starShape) + ' stroke-width:' + s.strokeWidth + 'px;" xml:space="preserve"><style type="text/css">.svg-empty-' + this._uid + '{fill:url(' + baseUrl + '#' + this._uid + '_SVGID_1_);}.svg-hovered-' + this._uid + '{fill:url(' + baseUrl + '#' + this._uid + '_SVGID_2_);}.svg-active-' + this._uid + '{fill:url(' + baseUrl + '#' + this._uid + '_SVGID_3_);}.svg-rated-' + this._uid + '{fill:' + s.ratedColor + ';}</style>' +
  169. this.getLinearGradient(this._uid + '_SVGID_1_', s.emptyColor, s.emptyColor, s.starShape) +
  170. this.getLinearGradient(this._uid + '_SVGID_2_', s.hoverColor, s.hoverColor, s.starShape) +
  171. this.getLinearGradient(this._uid + '_SVGID_3_', s.starGradient.start, s.starGradient.end, s.starShape) +
  172. this.getVectorPath(this._uid, {
  173. starShape: s.starShape,
  174. strokeWidth: s.strokeWidth,
  175. strokeColor: s.strokeColor
  176. } ) +
  177. '</svg></div>';
  178. // inject svg markup
  179. var starsMarkup = '';
  180. for( var i = 0; i < s.totalStars; i++){
  181. starsMarkup += star;
  182. }
  183. this.$el.append(starsMarkup);
  184. this.$stars = this.$el.find('.jq-star');
  185. },
  186. getVectorPath: function(id, attrs){
  187. return (attrs.starShape === 'rounded') ?
  188. this.getRoundedVectorPath(id, attrs) : this.getSpikeVectorPath(id, attrs);
  189. },
  190. getSpikeVectorPath: function(id, attrs){
  191. return '<polygon data-side="center" class="svg-empty-' + id + '" points="281.1,129.8 364,55.7 255.5,46.8 214,-59 172.5,46.8 64,55.4 146.8,129.7 121.1,241 212.9,181.1 213.9,181 306.5,241 " style="fill: transparent; stroke: ' + attrs.strokeColor + ';" />' +
  192. '<polygon data-side="left" class="svg-empty-' + id + '" points="281.1,129.8 364,55.7 255.5,46.8 214,-59 172.5,46.8 64,55.4 146.8,129.7 121.1,241 213.9,181.1 213.9,181 306.5,241 " style="stroke-opacity: 0;" />' +
  193. '<polygon data-side="right" class="svg-empty-' + id + '" points="364,55.7 255.5,46.8 214,-59 213.9,181 306.5,241 281.1,129.8 " style="stroke-opacity: 0;" />';
  194. },
  195. getRoundedVectorPath: function(id, attrs){
  196. var fullPoints = 'M520.9,336.5c-3.8-11.8-14.2-20.5-26.5-22.2l-140.9-20.5l-63-127.7 c-5.5-11.2-16.8-18.2-29.3-18.2c-12.5,0-23.8,7-29.3,18.2l-63,127.7L28,314.2C15.7,316,5.4,324.7,1.6,336.5S1,361.3,9.9,370 l102,99.4l-24,140.3c-2.1,12.3,2.9,24.6,13,32c5.7,4.2,12.4,6.2,19.2,6.2c5.2,0,10.5-1.2,15.2-3.8l126-66.3l126,66.2 c4.8,2.6,10,3.8,15.2,3.8c6.8,0,13.5-2.1,19.2-6.2c10.1-7.3,15.1-19.7,13-32l-24-140.3l102-99.4 C521.6,361.3,524.8,348.3,520.9,336.5z';
  197. return '<path data-side="center" class="svg-empty-' + id + '" d="' + fullPoints + '" style="stroke: ' + attrs.strokeColor + '; fill: transparent; " /><path data-side="right" class="svg-empty-' + id + '" d="' + fullPoints + '" style="stroke-opacity: 0;" /><path data-side="left" class="svg-empty-' + id + '" d="M121,648c-7.3,0-14.1-2.2-19.8-6.4c-10.4-7.6-15.6-20.3-13.4-33l24-139.9l-101.6-99 c-9.1-8.9-12.4-22.4-8.6-34.5c3.9-12.1,14.6-21.1,27.2-23l140.4-20.4L232,164.6c5.7-11.6,17.3-18.8,30.2-16.8c0.6,0,1,0.4,1,1 v430.1c0,0.4-0.2,0.7-0.5,0.9l-126,66.3C132,646.6,126.6,648,121,648z" style="stroke: ' + attrs.strokeColor + '; stroke-opacity: 0;" />';
  198. },
  199. getSvgDimensions: function(starShape){
  200. return (starShape === 'rounded') ? 'width="550px" height="500.2px" viewBox="0 146.8 550 500.2" style="enable-background:new 0 0 550 500.2;' : 'x="0px" y="0px" width="305px" height="305px" viewBox="60 -62 309 309" style="enable-background:new 64 -59 305 305;';
  201. },
  202. getLinearGradient: function(id, startColor, endColor, starShape){
  203. var height = (starShape === 'rounded') ? 500 : 250;
  204. return '<linearGradient id="' + id + '" gradientUnits="userSpaceOnUse" x1="0" y1="-50" x2="0" y2="' + height + '"><stop offset="0" style="stop-color:' + startColor + '"/><stop offset="1" style="stop-color:' + endColor + '"/> </linearGradient>';
  205. },
  206. executeCallback: function(rating, $el){
  207. var callback = this.settings.callback;
  208. callback(rating, $el);
  209. }
  210. };
  211. var publicMethods = {
  212. unload: function() {
  213. var _name = 'plugin_' + pluginName;
  214. var $el = $(this);
  215. var $starSet = $el.data(_name).$stars;
  216. $starSet.off();
  217. $el.removeData(_name).remove();
  218. },
  219. setRating: function(rating, round) {
  220. var _name = 'plugin_' + pluginName;
  221. var $el = $(this);
  222. var $plugin = $el.data(_name);
  223. if( rating > $plugin.settings.totalStars || rating < 0 ) { return; }
  224. if( round ){
  225. rating = Math.round(rating);
  226. }
  227. $plugin.applyRating(rating);
  228. },
  229. getRating: function() {
  230. var _name = 'plugin_' + pluginName;
  231. var $el = $(this);
  232. var $starSet = $el.data(_name);
  233. return $starSet._state.rating;
  234. },
  235. resize: function(newSize) {
  236. var _name = 'plugin_' + pluginName;
  237. var $el = $(this);
  238. var $starSet = $el.data(_name);
  239. var $stars = $starSet.$stars;
  240. if(newSize <= 1 || newSize > 200) {
  241. console.error('star size out of bounds');
  242. return;
  243. }
  244. $stars = Array.prototype.slice.call($stars);
  245. $stars.forEach(function(star){
  246. $(star).css({
  247. 'width': newSize + 'px',
  248. 'height': newSize + 'px'
  249. });
  250. });
  251. },
  252. setReadOnly: function(flag) {
  253. var _name = 'plugin_' + pluginName;
  254. var $el = $(this);
  255. var $plugin = $el.data(_name);
  256. if(flag === true){
  257. $plugin.$stars.off('mouseover mouseout click');
  258. } else {
  259. $plugin.settings.readOnly = false;
  260. $plugin.addListeners();
  261. }
  262. }
  263. };
  264. // Avoid Plugin.prototype conflicts
  265. $.extend(Plugin.prototype, methods);
  266. $.fn[ pluginName ] = function ( options ) {
  267. // if options is a public method
  268. if( !$.isPlainObject(options) ){
  269. if( publicMethods.hasOwnProperty(options) ){
  270. return publicMethods[options].apply(this, Array.prototype.slice.call(arguments, 1));
  271. } else {
  272. $.error('Method '+ options +' does not exist on ' + pluginName + '.js');
  273. }
  274. }
  275. return this.each(function() {
  276. // preventing against multiple instantiations
  277. if ( !$.data( this, 'plugin_' + pluginName ) ) {
  278. $.data( this, 'plugin_' + pluginName, new Plugin( this, options ) );
  279. }
  280. });
  281. };
  282. })( jQuery, window, document );