jquery.rating.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. /*
  2. ### jQuery Star Rating Plugin v4.11 - 2013-03-14 ###
  3. * Home: http://www.fyneworks.com/jquery/star-rating/
  4. * Code: http://code.google.com/p/jquery-star-rating-plugin/
  5. *
  6. * Licensed under http://en.wikipedia.org/wiki/MIT_License
  7. ###
  8. */
  9. /*# AVOID COLLISIONS #*/
  10. ;if(window.jQuery) (function($){
  11. /*# AVOID COLLISIONS #*/
  12. // IE6 Background Image Fix
  13. if ((!$.support.opacity && !$.support.style)) try { document.execCommand("BackgroundImageCache", false, true)} catch(e) { };
  14. // Thanks to http://www.visualjquery.com/rating/rating_redux.html
  15. // plugin initialization
  16. $.fn.rating = function(options){
  17. if(this.length==0) return this; // quick fail
  18. // Handle API methods
  19. if(typeof arguments[0]=='string'){
  20. // Perform API methods on individual elements
  21. if(this.length>1){
  22. var args = arguments;
  23. return this.each(function(){
  24. $.fn.rating.apply($(this), args);
  25. });
  26. };
  27. // Invoke API method handler
  28. $.fn.rating[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);
  29. // Quick exit...
  30. return this;
  31. };
  32. // Initialize options for this call
  33. var options = $.extend(
  34. {}/* new object */,
  35. $.fn.rating.options/* default options */,
  36. options || {} /* just-in-time options */
  37. );
  38. // Allow multiple controls with the same name by making each call unique
  39. $.fn.rating.calls++;
  40. // loop through each matched element
  41. this
  42. .not('.star-rating-applied')
  43. .addClass('star-rating-applied')
  44. .each(function(){
  45. // Load control parameters / find context / etc
  46. var control, input = $(this);
  47. var eid = (this.name || 'unnamed-rating').replace(/\[|\]/g, '_').replace(/^\_+|\_+$/g,'');
  48. var context = $(this.form || document.body);
  49. // FIX: http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=23
  50. var raters = context.data('rating');
  51. if(!raters || raters.call!=$.fn.rating.calls) raters = { count:0, call:$.fn.rating.calls };
  52. var rater = raters[eid] || context.data('rating'+eid);
  53. // if rater is available, verify that the control still exists
  54. if(rater) control = rater.data('rating');
  55. if(rater && control)//{// save a byte!
  56. // add star to control if rater is available and the same control still exists
  57. control.count++;
  58. //}// save a byte!
  59. else{
  60. // create new control if first star or control element was removed/replaced
  61. // Initialize options for this rater
  62. control = $.extend(
  63. {}/* new object */,
  64. options || {} /* current call options */,
  65. ($.metadata? input.metadata(): ($.meta?input.data():null)) || {}, /* metadata options */
  66. { count:0, stars: [], inputs: [] }
  67. );
  68. // increment number of rating controls
  69. control.serial = raters.count++;
  70. // create rating element
  71. rater = $('<span class="star-rating-control"/>');
  72. input.before(rater);
  73. // Mark element for initialization (once all stars are ready)
  74. rater.addClass('rating-to-be-drawn');
  75. // Accept readOnly setting from 'disabled' property
  76. if(input.attr('disabled') || input.hasClass('disabled')) control.readOnly = true;
  77. // Accept required setting from class property (class='required')
  78. if(input.hasClass('required')) control.required = true;
  79. // Create 'cancel' button
  80. rater.append(
  81. control.cancel = $('<div class="rating-cancel"><a title="' + control.cancel + '">' + control.cancelValue + '</a></div>')
  82. .on('mouseover',function(){
  83. $(this).rating('drain');
  84. $(this).addClass('star-rating-hover');
  85. //$(this).rating('focus');
  86. })
  87. .on('mouseout',function(){
  88. $(this).rating('draw');
  89. $(this).removeClass('star-rating-hover');
  90. //$(this).rating('blur');
  91. })
  92. .on('click',function(){
  93. $(this).rating('select');
  94. })
  95. .data('rating', control)
  96. );
  97. }; // first element of group
  98. // insert rating star (thanks Jan Fanslau rev125 for blind support https://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=125)
  99. var star = $('<div role="text" aria-label="'+ this.title +'" class="star-rating rater-'+ control.serial +'"><a title="' + (this.title || this.value) + '">' + this.value + '</a></div>');
  100. rater.append(star);
  101. // inherit attributes from input element
  102. if(this.id) star.attr('id', this.id);
  103. if(this.className) star.addClass(this.className);
  104. // Half-stars?
  105. if(control.half) control.split = 2;
  106. // Prepare division control
  107. if(typeof control.split=='number' && control.split>0){
  108. var stw = ($.fn.width ? star.width() : 0) || control.starWidth;
  109. var spi = (control.count % control.split), spw = Math.floor(stw/control.split);
  110. star
  111. // restrict star's width and hide overflow (already in CSS)
  112. .width(spw)
  113. // move the star left by using a negative margin
  114. // this is work-around to IE's stupid box model (position:relative doesn't work)
  115. .find('a').css({ 'margin-left':'-'+ (spi*spw) +'px' })
  116. };
  117. // readOnly?
  118. if(control.readOnly)//{ //save a byte!
  119. // Mark star as readOnly so user can customize display
  120. star.addClass('star-rating-readonly');
  121. //} //save a byte!
  122. else//{ //save a byte!
  123. // Enable hover css effects
  124. star.addClass('star-rating-live')
  125. // Attach mouse events
  126. .on('mouseover',function(){
  127. $(this).rating('fill');
  128. $(this).rating('focus');
  129. })
  130. .on('mouseout',function(){
  131. $(this).rating('draw');
  132. $(this).rating('blur');
  133. })
  134. .on('click',function(){
  135. $(this).rating('select');
  136. })
  137. ;
  138. //}; //save a byte!
  139. // set current selection
  140. if(this.checked) control.current = star;
  141. // set current select for links
  142. if(this.nodeName=="A"){
  143. if($(this).hasClass('selected'))
  144. control.current = star;
  145. };
  146. // hide input element
  147. input.hide();
  148. // backward compatibility, form element to plugin
  149. input.on('change.rating',function(event){
  150. if(event.selfTriggered) return false;
  151. $(this).rating('select');
  152. });
  153. // attach reference to star to input element and vice-versa
  154. star.data('rating.input', input.data('rating.star', star));
  155. // store control information in form (or body when form not available)
  156. control.stars[control.stars.length] = star[0];
  157. control.inputs[control.inputs.length] = input[0];
  158. control.rater = raters[eid] = rater;
  159. control.context = context;
  160. input.data('rating', control);
  161. rater.data('rating', control);
  162. star.data('rating', control);
  163. context.data('rating', raters);
  164. context.data('rating'+eid, rater); // required for ajax forms
  165. }); // each element
  166. // Initialize ratings (first draw)
  167. $('.rating-to-be-drawn').rating('draw').removeClass('rating-to-be-drawn');
  168. return this; // don't break the chain...
  169. };
  170. /*--------------------------------------------------------*/
  171. /*
  172. ### Core functionality and API ###
  173. */
  174. $.extend($.fn.rating, {
  175. // Used to append a unique serial number to internal control ID
  176. // each time the plugin is invoked so same name controls can co-exist
  177. calls: 0,
  178. focus: function(){
  179. var control = this.data('rating'); if(!control) return this;
  180. if(!control.focus) return this; // quick fail if not required
  181. // find data for event
  182. var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null );
  183. // focus handler, as requested by focusdigital.co.uk
  184. if(control.focus) control.focus.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
  185. }, // $.fn.rating.focus
  186. blur: function(){
  187. var control = this.data('rating'); if(!control) return this;
  188. if(!control.blur) return this; // quick fail if not required
  189. // find data for event
  190. var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null );
  191. // blur handler, as requested by focusdigital.co.uk
  192. if(control.blur) control.blur.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
  193. }, // $.fn.rating.blur
  194. fill: function(){ // fill to the current mouse position.
  195. var control = this.data('rating'); if(!control) return this;
  196. // do not execute when control is in read-only mode
  197. if(control.readOnly) return;
  198. // Reset all stars and highlight them up to this element
  199. this.rating('drain');
  200. this.prevAll().addBack().filter('.rater-'+ control.serial).addClass('star-rating-hover');
  201. },// $.fn.rating.fill
  202. drain: function() { // drain all the stars.
  203. var control = this.data('rating'); if(!control) return this;
  204. // do not execute when control is in read-only mode
  205. if(control.readOnly) return;
  206. // Reset all stars
  207. control.rater.children().filter('.rater-'+ control.serial).removeClass('star-rating-on').removeClass('star-rating-hover');
  208. },// $.fn.rating.drain
  209. draw: function(){ // set value and stars to reflect current selection
  210. var control = this.data('rating'); if(!control) return this;
  211. // Clear all stars
  212. this.rating('drain');
  213. // Set control value
  214. var current = $( control.current );//? control.current.data('rating.input') : null );
  215. var starson = current.length ? current.prevAll().addBack().filter('.rater-'+ control.serial) : null;
  216. if(starson) starson.addClass('star-rating-on');
  217. // Show/hide 'cancel' button
  218. control.cancel[control.readOnly || control.required?'hide':'show']();
  219. // Add/remove read-only classes to remove hand pointer
  220. this.siblings()[control.readOnly?'addClass':'removeClass']('star-rating-readonly');
  221. },// $.fn.rating.draw
  222. select: function(value,wantCallBack){ // select a value
  223. var control = this.data('rating'); if(!control) return this;
  224. // do not execute when control is in read-only mode
  225. if(control.readOnly) return;
  226. // clear selection
  227. control.current = null;
  228. // programmatically (based on user input)
  229. if(typeof value!='undefined' || this.length>1){
  230. // select by index (0 based)
  231. if(typeof value=='number')
  232. return $(control.stars[value]).rating('select',undefined,wantCallBack);
  233. // select by literal value (must be passed as a string
  234. if(typeof value=='string'){
  235. //return
  236. $.each(control.stars, function(){
  237. //console.log($(this).data('rating.input'), $(this).data('rating.input').val(), value, $(this).data('rating.input').val()==value?'BINGO!':'');
  238. if($(this).data('rating.input').val()==value) $(this).rating('select',undefined,wantCallBack);
  239. });
  240. // don't break the chain
  241. return this;
  242. };
  243. }
  244. else{
  245. control.current = this[0].tagName=='INPUT' ?
  246. this.data('rating.star') :
  247. (this.is('.rater-'+ control.serial) ? this : null);
  248. };
  249. // Update rating control state
  250. this.data('rating', control);
  251. // Update display
  252. this.rating('draw');
  253. // find current input and its sibblings
  254. var current = $( control.current ? control.current.data('rating.input') : null );
  255. var lastipt = $( control.inputs ).filter(':checked');
  256. var deadipt = $( control.inputs ).not(current);
  257. // check and uncheck elements as required
  258. deadipt.prop('checked',false);//.removeAttr('checked');
  259. current.prop('checked',true);//.attr('checked','checked');
  260. // trigger change on current or last selected input
  261. $(current.length? current : lastipt ).trigger({ type:'change', selfTriggered:true });
  262. // click callback, as requested here: http://plugins.jquery.com/node/1655
  263. if((wantCallBack || wantCallBack == undefined) && control.callback) control.callback.apply(current[0], [current.val(), $('a', control.current)[0]]);// callback event
  264. // don't break the chain
  265. return this;
  266. },// $.fn.rating.select
  267. readOnly: function(toggle, disable){ // make the control read-only (still submits value)
  268. var control = this.data('rating'); if(!control) return this;
  269. // setread-only status
  270. control.readOnly = toggle || toggle==undefined ? true : false;
  271. // enable/disable control value submission
  272. if(disable) $(control.inputs).attr("disabled", "disabled");
  273. else $(control.inputs).removeAttr("disabled");
  274. // Update rating control state
  275. this.data('rating', control);
  276. // Update display
  277. this.rating('draw');
  278. },// $.fn.rating.readOnly
  279. disable: function(){ // make read-only and never submit value
  280. this.rating('readOnly', true, true);
  281. },// $.fn.rating.disable
  282. enable: function(){ // make read/write and submit value
  283. this.rating('readOnly', false, false);
  284. }// $.fn.rating.select
  285. });
  286. /*--------------------------------------------------------*/
  287. /*
  288. ### Default Settings ###
  289. eg.: You can override default control like this:
  290. $.fn.rating.options.cancel = 'Clear';
  291. */
  292. $.fn.rating.options = { //$.extend($.fn.rating, { options: {
  293. cancel: 'Cancel Rating', // advisory title for the 'cancel' link
  294. cancelValue: '', // value to submit when user click the 'cancel' link
  295. split: 0, // split the star into how many parts?
  296. // Width of star image in case the plugin can't work it out. This can happen if
  297. // the jQuery.dimensions plugin is not available OR the image is hidden at installation
  298. starWidth: 16//,
  299. //NB.: These don't need to be pre-defined (can be undefined/null) so let's save some code!
  300. //half: false, // just a shortcut to control.split = 2
  301. //required: false, // disables the 'cancel' button so user can only select one of the specified values
  302. //readOnly: false, // disable rating plugin interaction/ values cannot be.one('change', //focus: function(){}, // executed when stars are focused
  303. //blur: function(){}, // executed when stars are focused
  304. //callback: function(){}, // executed when a star is clicked
  305. }; //} });
  306. /*--------------------------------------------------------*/
  307. // auto-initialize plugin
  308. $(function(){
  309. $('input[type=radio].star').rating();
  310. });
  311. /*# AVOID COLLISIONS #*/
  312. })(jQuery);
  313. /*# AVOID COLLISIONS #*/