Search code examples
javascriptjqueryeventsglobal-variables

trying to access number variable outside the function in jQuery


Creating Stars rating system and I want to access the rating number and perform an action based on that. How can I access the number variable outside my click function?

$(document).ready(function () {
            $(".li").mouseover(function () {
                var current = $(this);
                $(".li").each(function (index) {
                    $(this).addClass("hovered-stars");
                    if (index == current.index()) {
                        return false;
                    }
                })
            })
            $(".li").mouseleave(function () {
                $(this).removeClass("hovered-stars");
            })
            $(".li").click(function () {
                $(".li").removeClass("clicked");
                $(".hovered-stars").addClass("clicked");
                var number = $(".clicked").length;
                $("#message").html("You rated " + number + " Stars");
            })
            console.log(number);
        })

Currently cannot print number variable outside click event listener


Solution

  • you need to declare the number variable outside the click function and then re-assign the value inside click function

    $(document).ready(function () {
            var number=0;
            $(".li").mouseover(function () {
                var current = $(this);
                $(".li").each(function (index) {
                    $(this).addClass("hovered-stars");
                    if (index == current.index()) {
                        return false;
                    }
                })
            })
            $(".li").mouseleave(function () {
                $(this).removeClass("hovered-stars");
            })
            $(".li").click(function () {
                $(".li").removeClass("clicked");
                $(".hovered-stars").addClass("clicked");
                number = $(".clicked").length;
                $("#message").html("You rated " + number + " Stars");
            })
            console.log(number);
        })