0

I want to have a slider to control the size of the background-image property of a div, and I want the mininum value to fill the container regardless of the size (and proportion) of the image.

https://jsfiddle.net/ydt4fam2/9/

HTML

<div class="main"></div>

<div class="controls">
  <span>Size</span>
  <input type="range" class="i1" max="150">

  <span>Position X</span>
  <input type="range" class="i2">

  <span>Position Y</span>
  <input type="range" class="i3">
</div>

CSS

html, body{
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.main{
   background-image: url(https://picsum.photos/600/400/?image=355);
   width: 300px;
   height: 300px;
   border: 2px solid red;
   background-size: 100%;
   background-repeat: no-repeat;
   background-position: center;
}

.controls{
  width: 12rem;
  background: rgba(0,0,0,0.9);
  border-radius: 5px;
  padding: 1rem;
  color: #fff;
  top: 1rem;
  position: fixed;
  right: 1rem;
}

.controls span{
  width: 100%;
  display: block;
}

.controls input{
  margin-bottom: 1rem;
}

JS

$('.i1').on('input', inputSize);
$('.i2').on('input', inputX);
$('.i3').on('input', inputY);

function inputSize(){
    var val = $(this).val();
  $('.main').css('background-size', 'auto ' + val + '%');
}

function inputX(){
    var val = $(this).val();
  $('.main').css('background-position-x', val+'%');
}

function inputY(){
    var val = $(this).val();
  $('.main').css('background-position-y', val+'%');
}

Of course, I can use a min value in the slider (for example, 150) but if the image is too tall it still won't fill the div.

Any ideas?

Also, it shouldn't use more divs (for example, another div inside the .main), it can only use bg-image.

nick
  • 2,819
  • 5
  • 33
  • 69
  • Do you know the size of the image in advance? – Sebastian Speitel Mar 21 '18 at 21:25
  • Yes, they are multiple images and each one can have different sizes – nick Mar 21 '18 at 21:33
  • use this for getting minimum value for size: https://stackoverflow.com/questions/3098404/get-the-size-of-a-css-background-image-using-javascript and then you can pick the minimum value based on the biggest (width or height) – ICE Mar 21 '18 at 21:35

0 Answers0