Skip to content

Instantly share code, notes, and snippets.

@Lakshay-Batra
Last active July 11, 2020 04:58
Show Gist options
  • Select an option

  • Save Lakshay-Batra/b1d723828f53782b19af62a4502bd38e to your computer and use it in GitHub Desktop.

Select an option

Save Lakshay-Batra/b1d723828f53782b19af62a4502bd38e to your computer and use it in GitHub Desktop.
function Star(el, count, callback) {
    var value = 0;
    // Write a logic to create star rating problem
    document.querySelector(el).innerHTML = `<i id="1" class="fa fa-star-o"></i>
    <i id="2" class="fa fa-star-o"></i>
    <i id="3" class="fa fa-star-o"></i>
    <i id="4" class="fa fa-star-o"></i>
    <i id="5" class="fa fa-star-o"></i>`
    var targetStars = document.querySelectorAll("i");
    for (var i = 0; i < count; i++) {
        var flag = 1;
        var value = 0;
        targetStars[i].addEventListener("click", function () {
            flag = 0;
            var id = parseInt(this.id);
            for (var remove = 0; remove < count; remove++) {
                targetStars[remove].classList.add('fa-star-o');
                targetStars[remove].classList.remove('fa-star');
            }
            for (var j = id - 1; j >= 0; j--) {

                targetStars[j].classList.add('fa-star');
                targetStars[j].classList.remove('fa-star-o');
            }
            value = this.id;
            callback(parseInt(value));
        });
        targetStars[i].addEventListener("mouseover", function () {
            flag = 1
            var id = parseInt(this.id);
            for (var j = id - 1; j >= 0; j--) {
                targetStars[j].classList.add('fa-star');
                targetStars[j].classList.remove('fa-star-o');
            }
        });
        targetStars[i].addEventListener("mouseleave", function () {
            if (flag) {
                var id = parseInt(this.id);
                for (var k = id - 1; k >= value; k--) {
                    targetStars[k].classList.add('fa-star-o');
                    targetStars[k].classList.remove('fa-star');
                }
            }
        });
    }

}



function getStar(value) {
    document.getElementById("display-star").innerHTML = value;
}
new Star("#star", 5, getStar);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment