Reputation: 701
I write jQuery scripts for choosing rating
This is HTML code
<div class="rating clearfix">
<div class="stars">
<div class="stars_width"></div>
</div>
<input id="rating-input" type="hidden" value="8">
<input id="article-id" type="hidden" value="">
</div>
jQuery script
function starsMouseMove(n, el) {
var $el = $(el);
var i = $el.offset().left,
t = Math.floor((n.pageX - i)),
w;
if (t > 0 && t < 20) {
w = 20;
} else if (t >= 20 && t < 40) {
w = 40;
} else if (t >= 40 && t < 60) {
w = 60;
} else if (t >= 60 && t < 80) {
w = 80;
} else if (t >= 80 && t <= 100) {
w = 100;
}
$(".stars_width", $el).css("width", w + "%");
};
function starsSelect(n, el) {
var $el = $(el);
var i = $el.offset().left,
t = Math.floor((n.pageX - i)),
w;
if (t > 0 && t < 20) {
w = 20;
} else if (t >= 20 && t < 40) {
w = 40;
} else if (t >= 40 && t < 60) {
w = 60;
} else if (t >= 60 && t < 80) {
w = 80;
} else if (t >= 80 && t <= 100) {
w = 100;
}
$(".stars_width", $el).css("width", w + "%");
$el.parent().find('#rating-input').val(w / 10);
};
$(".stars_width").css("width", $("#rating-input").val() * 20 + "%");
$('.stars').hover(function(e) {
starsMouseMove(e, this);
}, function(e){
$(".stars_width").css("width", $("#rating-input").val() * 20 + "%");
});
$('.stars').click(function(e) {
starsSelect(e, this);
});
http://jsfiddle.net/tu8v3cnt/14/
I need to change rating on mouse moving over $('.stars')
but save it only after click. If rating was not chosen (clicked), I need to back a default value.
But I have a problem here, script works on click
properly, but it doesn't work on hover
the right way. How can I fix it?
And I have duplicated code in two function but I don't know how to write script without it.
Upvotes: 2
Views: 72
Reputation: 5361
Using a mousemove function seems to do the trick. For saving, it will only save when you click. If you mean saving the rating to article-id then change all the rating-input in the code to article-id
Demo
Code
function starsMouseMove(n, el) {
var $el = $(el);
var i = $el.offset().left,
t = Math.floor((n.pageX - i)),
w;
if (t > 0 && t < 20) {
w = 20;
$("#rating-input").val("1")
} else if (t >= 20 && t < 40) {
w = 40;
$("#rating-input").val("2")
} else if (t >= 40 && t < 60) {
w = 60;
$("#rating-input").val("3")
} else if (t >= 60 && t < 80) {
w = 80;
$("#rating-input").val("4")
} else if (t >= 80 && t <= 100) {
w = 100;
$("#rating-input").val("5")
}
$(".stars_width", $el).css("width", w + "%");
};
$(".stars_width").css("width", $("#rating-input").val() * 20 + "%");
$('.stars').mousemove(function(e) {
starsMouseMove(e, this);
});
$('.stars').click(function(e) {
alert($("#rating-input").val())
});
A shorthand of the Code can be to divide w with 20
$("#rating-input").val(w / 20);
Demo
Upvotes: 2