Home > Software design >  jQuery UI-slider animation does not work inside event
jQuery UI-slider animation does not work inside event

Time:08-09

I have a jQquery UI Slider in the browser:

<meta comntent="text/html;charset=utf-8" http-equiv="Content-Type">

<html>
    <head>

    <!-- favicon -->
    <link rel="shortcut icon" href="favicon.ico">

    <!-- JQuery -->
    <script src="script/jquery/jquery-3.6.0.min.js"></script>
    <script src="script/jquery-ui/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="script/jquery-ui/jquery-ui.css">

    <script>

        $(document).ready(function(){

            $("#slider1").slider({
                max:10,
                min:-10,
                step:1,
                value:-10,
                animate: 'true',
                animate: 3000,
            });
            $("#slider1").slider("value", 0);
            $("#slider1").on('slidechange', slideChangeEvent);
        });

        function slideChangeEvent(event, ui){

            $("#slider1").off('slidechange');
            $("#slider1").slider( "option", "value", 0 );
            $("#slider1").on('slidechange', slideChangeEvent);
        }
    </script>
    </head>
    <body>
        <div id="slider1"></div>
    </body>
</html>

The idea is that the slider stays at the middle. When the user pull it right or left and releases the slider, it will automatically move back to middle - Animated. But it moves back instantly, instead of animated. Can you show me what I did wrong in the code?

CodePudding user response:

Consider the following that uses the .animate() of jQuery:

$(function() {
  $("#slider1").slider({
    max: 10,
    min: -10,
    step: 1,
    value: -10,
    animate: 3000,
    change: function(e, ui) {
      var w = $(this).width();
      $(ui.handle).animate({
        left: (w / 2)
      }, 3000);
      ui.value = 0;
    }
  });
  $("#slider1").slider("value", 0);
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<div id="slider1"></div>

A similar example is discussed here: Animating slider handle when altering the jQuery UI slider value option?

Without the animation, the slider will just jump to the new value.

  • Related