Star Rating - javascript

4

I'm creating a star rating system for my app. After a bit of work I got a code on the net and modified it for my purposes. In it, there is a class 'full' that will fill the stars according to the user hover over them, and when he withdraws the mouse the stars come back empty. Each star has a score.

The problem is that in the code I got it inserts into the database when the user clicks on the star, and in my case I have a button to send the data. That is, I need to when the user clicks on the star, save the score of it to use later when the user press the button, show the full stars as far as he clicked and when he draws the mouse from the div does not come back all empty . And as I've mentioned before, I'm pretty bad at javascript. If anyone of you can give a little help or some tips I am very grateful. Here is the code I used so far:

$(function () {
    $('.star').on('mouseover', function () {
        var indice = $('.star').index(this);
        $('.star').removeClass('full');
        for (var i = 0; i <= indice; i++) {
            $('.star:eq(' + i + ')').addClass('full');
        }
    });

    $('.star').on('mouseout', function () {
        $('.star').removeClass('full');
    });

    $('.star').on('click', function () {
        var ponto = $(this).attr('id');
        alert(ponto); // Esta parte é só uma forma para eu manter o controle, para saber se o ponto corresponde a estrela clicada  
    });
});

NOTE:

star is the name of the div where the stars are; full is the class that fills the stars; each star image has an id, with a different score;

    
asked by anonymous 26.09.2015 / 01:22

1 answer

3

Here's a suggestion:

$(function(){
    var estrelas = $('.star');
    var escolhida = 0;

    function repaint(e){
        var indice = $(this).index() + 1;
        if (e.type == 'click') escolhida = indice;
        estrelas.removeClass('full');
        var upTo = $(this).hasClass('star-wrapper') ? escolhida : indice;
        estrelas.slice(0, upTo).addClass('full');
    }

    $('.star-wrapper').on('mouseleave', repaint);
    estrelas.on('mouseenter mouseleave click', repaint);
});

jsFiddle: link

This example uses sprites , ie images .png that changes position to show the full star.

I made a version that uses the same repaint function for all events, so the code gets smaller. I think the code is self-explanatory. You may have questions here:

var upTo = $(this).hasClass('star-wrapper') ? escolhida : indice;
estrelas.slice(0, upTo).addClass('full');

The idea here is to use .slice() to only add the class to the chosen element. And if it is a mouseleave in .star-wrapper then it should be the chosen star and not the last one that had the mouse over.

And how to use this later, in another function?

Since the variable escolhida is available in the scope of this $(function(){ you only need to put the new code in the following code and use the value of escolhida .

    
26.09.2015 / 10:23