Giter VIP home page Giter VIP logo

fredolss / rater-js Goto Github PK

View Code? Open in Web Editor NEW
75.0 8.0 13.0 1.01 MB

Star rating widget for the browser. Unlimited number of stars. No dependencies. No Jquery required.

Home Page: https://fredolss.github.io/rater-js/

License: MIT License

HTML 11.03% JavaScript 87.01% CSS 1.96%
rater-js star-rating-widget star-rating star-rating-component star-ratings javascript rating star widget js

rater-js's Introduction

Rater Js

rater-js Logo Donate NPM version License Downloads Build Status

rater-js is a star rating widget for the browser.

Main features:

  • Unlimited number of stars.
  • Svg as background image makes it look good in any size.
  • Custom css. Use your own image as star.
  • RTL support.
  • Touch support.

Try Rater JS Demo โ†’

Installation

npm install rater-js --save

Usage

rater-js can be used with amd, commonjs or without any module loader using global scope.

In your html create an element that acts as the placeholder for the widget.

<div id="rater"></div>

Global scope

Directly reference the js from the module

<!--Add js before end body tag-->
<script src="node-modules/rater-js/index.js"></script>

The widget will be available globally as "raterJs" on the window object.

Node/Browserify

Just require the module.

var rater = require("rater-js");

Lastly we can use the widget like this:

 var myRater = rater({element: document.querySelector("#rater"), rateCallback: function rateCallback(rating, done) {
                //make async call to server however you want
                //in this example we have a 'service' that rate and returns the average rating
                myDataService.rate(rate).then(function(avgRating) {
                    //update the avarage rating with the one we get from the server
                    myRater.setRating(avgRating);
                     //we could disable the rater to prevent another rating
                     //if we dont want the user to be able to change their mind
                    myRater.disable();
                    //dont forget to call done
                    done();
                }, function(error) {
                        //handle the error
                        //dont forget to call done
                        done();
                });
	}});

Css will be injected at runtime, but you can override the css to get the look you want.

//change the whole image used as the star. Make sure to set starSize in options if not 16px.
//first image is for the 'off' mode
.star-rating {
        background: url("myStar_off.svg") !important;
}

//add style for 'on' mode
.star-rating .star-value{
        background: url("myStar_on.svg") !important;
}

Configuration

Property Description
element HtmlElement. Required.
rateCallback Function. Triggered when star i clicked.
max Number. Number of stars to show.
showToolTip true/false. If set to true, show tooltip when hover the stars.
starSize Number. Width and height of the star image.
disableText Text to show when disabled.
ratingText Text to show when hover over stars. Text {rating} {maxRating}.
isBusyText Displayed while user is rating but done not called yet.
readOnly true/false. If set to true, will disable the rater.
step Number. Set a precision between 0 and 1 for the rating.
reverse true/false. If set to true, the ratings will be reversed.

Methods/Properties

disable(): //Disable the widget
enable(): //Enable the widget
setRating(rating:number): //Set the rating
getRating(): //Get the average rating
dispose(); //Removes event handlers
clear(); //Clears the rating
element; //Get the element used by rater js

rater-js's People

Contributors

dependabot[bot] avatar fredolss avatar hyuri avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rater-js's Issues

More than one element

Hello! thanks for your repo, works good.

Im trying to manage multiple ratings on the same page so I changed the id for a class but I'm struggling to make it work. Stars are being used ok on the first element, thats all.

Thanks in advance

Average rating

Hi @fredolss

Got another question - Just wondering about the average rating. Saw that other issue btw talking about this.

What I'm wondering is:

Does the widget have support for decimal rating in the actual rendering of the SVG icon?

Here is an example of what I'm talking about:

https://imgur.com/kUd2Wsy

Imporvement recommendation

Hello, I was really thrilled with your plugin, and want thank you for your work. On my side, I would like to ask you add a new feature, let's name that prop "resetOnHover". Some details:

  • When user hover stars, we highlight selected stars;
  • When user clicks, we apply setRating() method;
  • When user hovers again on same stars, we START highlighting selected stars
  • If user did NO click and did blur from stars, we show PREVIOUS rating;
  • If user hovers and clicks, we apply setRating() method

I managed to do it dummy way by

  1. function onStarClick(e)
    I commented

// if (isRating === true) {
// return;
// }

then
2. function onMouseMove(e)
// if (disabled === true || isRating === true) {
// return;
// }

And it worked as I wanted, but I suppose that feature will be required. Thanks.

Rating not working on mobile phone (when using a pop-up box)

Hi,

First of all, thank you for this incredibly useful widget.

In the project I am working on, users can rate some objects based on several criteria. To do so, they have to click on a button which triggers a pop-up box (see screenshot 1). Everything is working fine on computer, but not on mobile phone. I get the following error (screenshot 2): "Value not set".

If found the culprit which is the following the line:
xCoor = e.changedTouches[0].pageX - e.changedTouches[0].target.offsetLeft;

Actually, e.changedTouches[0].target.offsetLeft is supposed to return the target element's position relative to the document, but it returns something else in my case (due to the pop-up box) and the condition (percent < 101) is never met.

Here a working solution to this edge case:

if (isTouch) {
    var getOffsetLeft = function(elem) {
        var offsetLeft = 0;
        do {
            if (!isNaN(elem.offsetLeft)) {
                offsetLeft += elem.offsetLeft;
            }
        } while (elem = elem.offsetParent);
        return offsetLeft;
    };

    xCoor = e.changedTouches[0].pageX - getOffsetLeft(e.changedTouches[0].target);
}

Could you please make the changes?

Thanks in advance,

Screenshot 1:
Sans titre

Screenshot 2:
Sans titre

Reset rater-js

How do I reset the rater after a user has rated something once?

Do I call dispose() and then reinitialize the rater object? Or can I disable and then enable it using disable() and enable()? Or do I just set the rating back to 0 with setRating()?

rater-js as a standalone library ?

Hi,
Thanks for the clean repo !
It needs requirejs to be used though, would it be possible to implement as a standalone library ?
Cheers

Decimal rating vertically instead of horizontally

Last question I believe :)

Is it possible to make the rendering of the decimal rating vertically instead of the regular horizontally?

I'm asking because the icon I'm using is a menstrual cup and it would be cool if you could actually think of the decimals as a way of "filling the cup" if you know what I mean.

If you're busy, you could point me to the right section in the code, give me some pointers and I can try to create a pull request.

RTL support?

Hi, is it possible to add support for rtl languages?

Best,
Dario

Outdated types definitions

The type definitions in the ndex.d.ts file are outdated

  • Missing the readOnly property
  • Typo in the setRating function argument change ratig to rating
  • rateCallback should be (rating: number, done?: () => any) => any

Not a priority but it causes typescript errors on my end.

Question about ajax response

Hi, I've this code, inside a rateCallback function:

`

raterJs({

        starSize: starSize,
        step: 1,
        showToolTip: false,
        rating: mediumRating,
        readOnly: readonly,
        element: document.querySelector("#visitor-votes-rater"),

        rateCallback: function rateCallback(rating, done) {

        var rating = rating.toFixed(1);
        var rating = parseFloat(rating);

        var data = {
            action: 'send_visitor_rating',
            rating: rating,
            post_id: CommonData.postid,
            size: starSize,
        };

        var dataToSend = jsObject_to_URLEncoded(data);

        var VVAjaxCall = new Request(CommonData.ajaxurl ,{
            method: 'post',
            headers: new Headers({
                "Content-Type": "application/x-www-form-urlencoded"
            }),
            body: dataToSend
        });

        fetch(VVAjaxCall)

            .then (function(response) {

                if (response.status !== 200) {
                    console.log('Looks like there was a problem. Status Code: ' +
                        response.status);
                    return;
                }

                response.json().then(function(data) {
                    var rater = document.querySelector("#visitor-votes-rater");

                    rater.setRating(data);
                });


            })

            .catch(function(err) {
                console.log('Fetch Error :-S', err);
            });


        done();
    }


});`

Data is a number with the average rating, but seems like the stars set doesn't update the vote.

What am I doing wrong?

Best,
Dario

ES support

Hello,

Is it possible to include ES Modules support?

That way, we could just import { foo } from 'rater-js' the widget in our apps :)

Cheers

Allow a decimal rating

Hello,
is it possible to rate an item with decimal precision?

A new configuration proprerty, something like "step" or similiar will be awesome, e.g.

step: 0.1 // 0.1 deciamal precision
step: 0.5 // half int precision

Apologize for my English :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.