I am creating a star rating function using the code from the Sitepoint JQuery Novice to Ninja book and it works great… except
I am refreshing data on the page using jquery and when the data is refreshed, the function does not apply itself to the new data. I assume I need to use the live() method but am not quite sure where to place it.
I have used it before with click but in the code below, do I need to put in several live() methods, one for click, one for hover, etc. or just one for the create:. And even if I do the click and hover, that still doesn’t take care of the function creation, right? Thanks for any help on this.
var starRating = {
create: function(selector) {
// loop over every element matching the selector
$(selector).each(function() {
var $list = $('<div></div>');
// loop over every radio button in each container
$(this).find('input:radio').each(function(i) {
var rating = $(this).parent().text();
var $item = $('<a href="#"></a>').attr('title', rating).addClass(i % 2 == 1 ? 'rating-right' : '').text(rating);
starRating.addHandlers($item);
$list.append($item);
if($(this).is(':checked')) {
$item.prevAll().andSelf().addClass('rating');
}
});
// Hide the original radio buttons
$(this).append($list).find('label').hide();
});
},
addHandlers: function(item) {
$(item).click(function(e) {
// Handle Star click
var $star = $(this);
var $allLinks = $(this).parent();
// Set the radio button value
$allLinks.parent().find('input:radio[value=' + $star.text() + ']').attr('checked', true);
$x = $star.text().length;
rating = $star.text().substr(0, $x - 6);
// Set the ratings
$allLinks.children().removeClass('rating');
$star.prevAll().andSelf().addClass('rating');
// prevent default link click
e.preventDefault();
}).hover(function() {
// Handle star mouse over
$(this).prevAll().andSelf().addClass('rating-over');
}, function() {
// Handle star mouse out
$(this).siblings().andSelf().removeClass('rating-over')
});
}
}