Search code examples
javascriptjquerysliderrangeslider

Create multiple sliders with JQuery automatically


I was trying to make N sliders with JQuery in more automatic way using iteration and I have a few questions (working example is at the end).

Why does the first JQuery code work but second JS code does not work for producing multiple sliders? Shouldn`t this iterate over arr in the same way? Is there any other possible way to use JS for looping and pass arguments to JQuery for making sliders?

JQuery:

  var arr = [ "1" , 2, 3, 4];
  jQuery.each( arr, function( i, val ) {
    $( function() {
        $( "#slider"+val ).slider();
    } );
  });

And JS code:

for(var i=0; i<4; i++){
    $( function() {
        $( "#slider"+arr[i] ).slider();
    } );
  }

Here is the code in a simple example .

var arr = ["1", 2, 3, 4]; // 

jQuery.each(arr, function(i, val) {
  console.log("#slider" + val)
  $(function() {
    $("#slider" + val).slider();
  });
});

/*for(var i=0; i<4; i++){
  $( function() {
      $( "#slider"+arr[i] ).slider();
  } );
}*/
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="slider1"></div>
<div id="slider2"></div>
<div id="slider3"></div>
<div id="slider4"></div>


Solution

  • Why do the iteration yourself? Let jQuery do the work

    Also $(function() {}) is an alternative to $(document).ready(function(){}) so you complicate things far too much

    $(function() {
      $(".slider").slider();
    })
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <div class="slider" id="slider1"></div>
    <div class="slider" id="slider2"></div>
    <div class="slider" id="slider3"></div>
    <div class="slider" id="slider4"></div>

    If you WANT to loop, loop over the existing elements

    $(function() {
      $(".slider").each(function() { $(this).slider() })
    })
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <div class="slider" id="slider1"></div>
    <div class="slider" id="slider2"></div>
    <div class="slider" id="slider3"></div>
    <div class="slider" id="slider4"></div>