Search code examples
javascriptarrayspage-refreshrangeslider

How do I set a default image on a range slider with images


I have range slider which flicks through images and gives a number.

When I refresh the page the image shows up blank.

How do I set a default image so that when I refresh the page the image shows on load.

link to codepen https://codepen.io/jameswill77/pen/mdxBaQN

    var imageUrl = new Array();

        imageUrl[0] = 'https://static.pexels.com/photos/39517/rose-flower-blossom-bloom-39517.jpeg';

        imageUrl[500] = 'https://static.pexels.com/photos/36764/marguerite-daisy-beautiful-beauty.jpg';

        imageUrl[1000] = 'https://static.pexels.com/photos/39517/rose-flower-blossom-bloom-39517.jpeg';

        imageUrl[1500] = 'https://static.pexels.com/photos/39517/rose-flower-blossom-bloom-39517.jpeg';

        imageUrl[2000] = 'https://static.pexels.com/photos/36764/marguerite-daisy-beautiful-beauty.jpg';

        imageUrl[2500] = 'https://static.pexels.com/photos/39517/rose-flower-blossom-bloom-39517.jpeg';

        imageUrl[3000] = 'https://static.pexels.com/photos/36764/marguerite-daisy-beautiful-beauty.jpg';
       
$(document).on('input change', '#slider', function() {//listen to slider changes
    var v=$(this).val();//getting slider val
   $('#sliderStatus').html( $(this).val() );
  $("#img").prop("src", imageUrl[v]);
});

Solution

  • The image element is not given an image URL until the slider is moved. To set a default image, you could provide the image element an image source with the src attribute in the HTML.

     <img class="graph-image" src="https://static.pexels.com/photos/39517/rose-flower-blossom-bloom-39517.jpeg" style='width:600px;height:600px;' id='img'/>

    Alternatively, you could set the default image in Javascript by adding $("#img").prop("src", imageUrl[0]); right above the slider event class.