JavaScript - Resize Images with a Slider

From NoskeWiki
Jump to navigation Jump to search
Slider resizes all images (matching a classname)


NOTE: This page is a daughter page of: JavaScript

The slider below resize all images matching a drop down. It builds on my CSS - Centered Thumbnail Display page.

Slider to resize images, including center cropping example



  .image_box {
    background-color: #fafafa;
    height: 160px;
    width: 160px;
    border-style: solid;
    border-width: 1px;
    border-color: #eaeaea;
    display: inline-block;
    position: relative;
  .image_thumbnail {
    max-height: 100%;
    max-width: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  .center_cropped {
    object-fit: cover;         /* Scale the image so it covers whole area */
    object-position: center;   /* Center the image within the element */
    height: 100%;
    width: 100%;

   * Resizes all `image_box` div/images.
   * @param {Number} rangeValue Slider value between 1 and 100.
  function changeImageSizeWithSlider(sideLength)
    var sideLengthStr = (sideLength + "px");
    var imageBoxes = document.getElementsByClassName("image_box");

    for (var i = 0; i < imageBoxes.length; i++) {
      imageBoxes[i].style.width = sideLengthStr;
      imageBoxes[i].style.height = sideLengthStr;
    // Little images look nicer when center cropped:
    var centerCrop = sideLength < 150;
   * Center crops all `image_thumbnail` div/images or not.
   * @param {bool} centerCrop Whether to apply center crop.
  function changeImagesToCenterCrop(centerCrop)
    var imageBoxes = document.getElementsByClassName("image_thumbnail");
    for (var i = 0; i < imageBoxes.length; i++) {
      if (centerCrop) {
      } else {


  Resize images below:
  <input type="range" min="50" max="500" value="160"
         class="slider" id="range-image-size"
         oninput="changeImageSizeWithSlider(this.value)"> <br><hr>

  <div class="image_box"><img src="" class="image_thumbnail"></div>
  <div class="image_box"><img src="" class="image_thumbnail"></div>

Code license
For all of the code on my site... if there are specific instruction or licence comments please leave them in. If you copy my code with minimum modifications to another webpage, or into any code other people will see I would love an acknowledgment to my site.... otherwise, the license for this code is more-or-less WTFPL (do what you want)! If only copying <20 lines, then don't bother. That said - if you'd like to add a web-link to my site or (better yet) the specific page with code, that's a really sweet gestures! Links to the page may be useful to yourself or your users and helps increase traffic to my site. Hope my code is useful! :)