JSFiddle - React, Tailwind, and code Playground
by kougiland
HTML
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<div data-bind="rating: bewertung"></div>
CSS
.starRating{
text-align: center;
direction: ltr;
}
.starRating span{
width:84px;
height:64px;
cursor:pointer;
position:relative;
display:inline-block;
font-size: 4em;
line-height: 1.1em;
color:#ccc;
transition:color 300ms ease-in-out;
}
.chosenStar,.hoverRating{
color:orange!important;
}
JavaScript
ko.bindingHandlers.rating = {
init: function(element, valueAccessor) {
$(element).addClass("starRating");
for (var i = 0; i < 5; i++)
$(element).append("<span>★");//("<span>☆");
$("span", element).each(function(index) {
$(this).hover(
function() { $(this).prevAll().add(this).addClass("hoverRating") },
function() { $(this).prevAll().add(this).removeClass("hoverRating") }
).click(function(i) {
var observable = valueAccessor();
observable(index+1);
var rate = $(this).index();
console.log(rate+1);
});
});
},
update: function(element, valueAccessor) {
var observable = valueAccessor();
$("span", element).each(function(index) {
$(this).toggleClass("chosenStar", index < observable());
});
}
};
var viewModel = {
bewertung: ko.observable(2)
};
/****************alternative*1****************************
var bewertung = ko.observable(4);
var viewModel = {
bewertung: bewertung
};
*****************alternative*2****************************
function bewertungsWert() {
return bewertung = ko.observable(4);
}
var viewModel = {
bewertungsWert: bewertungsWert([""])
};
*****************alternative*3****************************
var viewModel = {
bewertung: ko.observableArray([])
};
viewModel.bewertung = ko.observable(4);
********************************************/
ko.applyBindings(viewModel);