Commits

Marko Vuksanovic  committed 2c9168d

Simple jquery rating plugin

  • Participants
  • Parent commits 9465597

Comments (0)

Files changed (1)

File jquery.rating.js

+(function($) {
+
+	var methods = {
+		init: function(options) {
+
+			var settings = $.extend({
+				'ratingDescription': ['none', 'poor', 'so so', 'average', 'good', 'amazing'],
+				'hint': '#hint' 
+			}, options);
+
+
+			var getDescriptionForRating = function(rating) {
+				return settings.ratingDescription[rating + 1];
+			}
+
+			var getSelectedIndex = function(element) {
+				var selectedIndex = element.attr("data-selected-index");
+				if (typeof selectedIndex === 'undefined') selectedIndex = -1;
+				return parseInt(selectedIndex);
+			}
+
+			for ( var i = 0; i<5; i++) {
+				this.append($('<div>').
+					addClass("star").
+					attr("data-index", i).
+					mouseover(function(e) {
+						$(this).trigger("star-hover.rating");
+					})
+					.click(function(event) {
+						$(this).parent().attr("data-selected-index", $(this).attr('data-index'))
+					}));
+			}
+			this.mouseleave(function() {
+				$(this).trigger("star-leave.rating");	
+			})
+
+			// When hover over a star
+			this.on('star-hover.rating', 'div', function(event) {
+				$(settings.hint).trigger("star-hover.rating", parseInt($(this).attr('data-index') ));
+				$(this).siblings().each(function(index) {
+					$(this).removeClass("star-hover");	
+				});
+				$(this).addClass("star-hover");
+				$(this).prevAll().each(function() {
+					$(this).addClass("star-hover")
+				})
+			});
+
+			// When leaving the container which holds all the stars
+			this.on('star-leave.rating', function(event) {
+				var selectedIndex = getSelectedIndex($(this));
+				$(settings.hint).trigger('selected-index-event.rating', selectedIndex );
+				$(this).children().each(function(index) {
+					if (index > selectedIndex) {
+						$(this).removeClass("star-hover");
+					} else {
+						$(this).addClass("star-hover");
+					}	
+				});
+			});
+			$(settings.hint).on('selected-index-event.rating', function(event, data) {
+				// TODO this causes a full repaint.
+				$(settings.hint).text(getDescriptionForRating(data));
+			})
+			$(settings.hint).on('star-hover.rating', function(event, data) {
+				// TODO this causes a full repaint
+				$(settings.hint).text(getDescriptionForRating(data));
+			})
+
+			// Fire event that nothing has been selected
+			$(settings.hint).trigger('selected-index-event.rating', -1 );
+
+			return this;
+		},
+		score: function() {
+			return parseInt($(this).attr("data-selected-index"));
+		}
+	}
+
+	$.fn.rating = function( method ) {
+		if ( methods[method] ) {
+			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
+		} else if ( typeof method === 'object' || ! method ) {
+			return methods.init.apply( this, arguments );
+		} else {
+			$.error( 'Method ' +  method + ' does not exist on jQuery.rating' );
+		} 
+	}
+})(jQuery);