Search code examples
jqueryhtmljscript

Issue with slider bars not adding together the correct value to then switch images


The following code is meant to add all the slider bars totals together and then switch images depending what level has been reached. At the moment it only appears to work with switching to the first level, any higher than 50 and the image doesnt change. What have i missed?

       <script>
       $(function() {
      $( ".slider" ).slider({
    orientation: "vertical",
    range: "min",
    min: 0,
    max: 100,
    value: 0,
    slide: function( event, ui ) {
 var total = 0;
$('.slider').each( function() {
    total += $(this).slider('value');
});

var img = 'img1.jpg';
if( total<=100 ) img = 'img1.jpg';
else if( total>=200 ) img = 'img2.jpg';
else if( total>=300 ) img = 'img3.jpg';
else if( total>=400 ) img = 'img4.jpg';
else if( total>=500 ) img = 'img5.jpg';

 ;

   $('#amount-img').attr( 'src', 'img/'+img );
  }
 });
   });


  </script>

Solution

  • You need to change the order of your conditions:

    if( total>=150 ) img = 'img1.jpg';
    else if( total>=100 ) img = 'img3.jpg';
    else if( total>=50 ) img = 'img2.jpg';
    

    otherwise the first one was true for all cases