Search code examples
jqueryjquery-ui-slider

JQuery Slider doesn't get its values updated correctly when called dynamically


I'm calling container.slider(...) dynamically and only getting the correct look when it gets called for the first time. How do I fix it?

Update - Clearly the demo is a quick hack reproducing the problem, let's not pick at using global vars etc unless it relates to the problem.

Repro (press the button a few times):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html style="height: 100%;">
<head>
    <title></title>
    <link href="styles/themes/ui-lightness/jquery-ui-1.9.0.custom.min.css" rel="stylesheet"
        type="text/css" />
    <script src="scripts/external/jquery-1.8.2.min.js" type="text/javascript"></script>
    <script src="scripts/external/jquery-ui-1.9.0.custom.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function () {
            //
            var longValues = [10, 50, 90];
            var shortValues = [50];
            var mode;

            function setLong() {
                $("#c").slider({ orientation: "horizontal", range: false, values: longValues, min: 0, max: 100, step: 1 });
                mode = "long";
            }

            function setShort() {
                $("#c").slider({ orientation: "horizontal", range: false, values: shortValues, min: 0, max: 100, step: 1 });
                mode = "short";
            }


            $("#t").on("click", function () {


                if (mode == "long") {
                    console.log("set short");
                    setShort();

                }
                else {
                    console.log("set long");
                    setLong();
                }
            });

            setLong();

        });
    </script> 
</head>
<body style="height: 100%;">

   <div id="c" style="width: 200px; vertical-align: middle;">
   </div>

   <button id="t">Toggle
   </button>
</body>
</html>

Solution

  • When changing the number of handles, it seems the old handles are not removed, and to "reset" the slider, you probably have to destroy it first:

    function setLong() {
        $("#c").slider( "destroy" );
        $("#c").slider({ orientation: "horizontal", 
                               range: false, 
                              values: longValues, 
                                 min: 0, 
                                 max: 100, 
                                step: 1 
        });
        mode = "long";
    }
    

    This seems to work, but there could be issues with destroying and initializing sliders like this, and it's not really properly tested or anything.

    FIDDLE