Last active
November 15, 2015 19:13
-
-
Save dzerrenner/9952b9dc179f4ee5e773 to your computer and use it in GitHub Desktop.
This could be used for some jquery star ratings. Backend communication is done via signals. See code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Can be used to implement star ratings. | |
HTML: | |
<div data-rating data-value="0..5"></div> | |
emits 'ratingChanged' if a star was clicked | |
updates stars if 'changeComplete' event is received. | |
CSS: | |
div[data-rating] > i.fa-star { color: goldenrod; } | |
div[data-rating] > i.fa-star-o { color: lightblue; } | |
i[data-index]:hover { color: gold !important; } | |
This makes full stars dark gold, empty stars light blue and the hovered star bright gold. | |
The CSS classes that are applied are 'fa fa-star' for full stars and 'fa fa-star-o' for empty stars. | |
This matches to the star icons of Font Awesome (http://fontawesome.io). | |
external JS: | |
$('div[data-rating]').on('ratingChanged', function() { | |
var self = $(this); | |
// additional attibute data-recipe-id in div container | |
$.post('/recipe/rating/'+self.data('recipe-id')+'/'+self.data('value')).done(function() { | |
self.trigger('changeComplete'); | |
}); | |
}); | |
*/ | |
(function($) { | |
var create_star = function(parent, value) { | |
var el = $('<i data-index="'+value+'" class="fa"></i>'); | |
if (value <= parent.data('value')) { | |
el.addClass('fa-star'); | |
} else { | |
el.addClass('fa-star-o'); | |
} | |
return el; | |
}; | |
$(function() { | |
$('div[data-rating]').each(function() { | |
var self = $(this); | |
var value = self.data('value'); | |
// this used to be an iteration over underscore's _.range | |
self.append(create_star(self, 1)); | |
self.append(create_star(self, 2)); | |
self.append(create_star(self, 3)); | |
self.append(create_star(self, 4)); | |
self.append(create_star(self, 5)); | |
}).on('changeComplete', function() { | |
var self = $(this); | |
$('i[data-index]', self).each(function(idx) { | |
var el = $(this); | |
if (idx < self.data('value')) { | |
el.addClass('fa-star').removeClass('fa-star-o'); | |
} else { | |
el.addClass('fa-star-o').removeClass('fa-star'); | |
} | |
}); | |
}); | |
// make stars clickable | |
$('i[data-index]', 'div[data-rating]').on('click', function() { | |
var self = $(this); | |
var parent = self.parent(); | |
// set data-value on container div | |
parent.data('value', self.data('index')); | |
// trigger event for external subscribers | |
parent.trigger('ratingChanged'); | |
}); | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment