Create Image slider using Js and CSS

anomaly3108

anomaly3108

Posted on January 1, 2022

Create Image slider using Js and CSS

In this article, we are going to make an Image Slider with a clean UI and smooth transition. First, Let's see what are we building.

PREVIEW

Image description

HTML

<div class="container">
     <div class="img-comp-container">
          <div class="img-comp-img">
               <img src="a.png" height="400" width="300">
          </div>
          <div class="img-comp-img img-comp-overlay">
               <img src="b.png" height="400" width="300">
          </div>
     </div>
</div>
Enter fullscreen mode Exit fullscreen mode

We will have an outer div with class .img-comp-container. It will have two separate children.

  • .img-comp-img: It will contain the first image.
  • .img-comp-overlay: It will contain the second image for overlay. This image will be overlayed over the top of first image to create the effect of sliding.

I guess now you have an overview of what are we doing. Now let's get into the CSS.

CSS

* {
    box-sizing: border-box;
}

.img-comp-container {
    position: relative;
    height: 500px;
}

.img-comp-img {
    position: absolute;
    width: auto;
    height: auto;
    overflow: hidden;
}

.img-comp-img img {
    padding: 20px;
    display: table-row;
}
.container {
    display: table;
}
Enter fullscreen mode Exit fullscreen mode

This CSS is for the image that will be displayed on the screen.
Everything above is self-explanatory but If you have any queries then comment down.

.img-comp-slider {
    position: absolute;
    z-index: 9;
    cursor: ew-resize;
    /*set the appearance of the slider:*/
    width: 40px;
    height: 40px;
    background: url(slider_icon.jpg);
    background-color: #ffffff70;
    background-repeat: round;
    backdrop-filter: blur(5px);
    border-radius: 50%;
}
Enter fullscreen mode Exit fullscreen mode

this CSS is for the slider button

Javascript

This is where the fun begins. Let's see from the scratch.
First, we need to find all elements with an "overlay" (img-comp-overlay) class

var x, i;
    /*find all elements with an "overlay" class:*/
    x = document.getElementsByClassName("img-comp-overlay");
    for (i = 0; i < x.length; i++) {
        /*once for each "overlay" element:
        pass the "overlay" element as a parameter when executing the compareImages function:*/
        compareImages(x[i]);
    }
Enter fullscreen mode Exit fullscreen mode

Next, we will create a function compareImages with an img parameter

function compareImages(img) {
   var slider, img, clicked = 0, w, h;
   /*get the width and height of the img element*/
   w = img.offsetWidth;
   h = img.offsetHeight;
   /*set the width of the img element to 50%:*/
   img.style.width = (w / 2) + "px";
}
Enter fullscreen mode Exit fullscreen mode

Now, We will create the slider using Js in the same function

/*create slider:*/
slider = document.createElement("DIV");
slider.setAttribute("class", "img-comp-slider");
/*insert slider*/
img.parentElement.insertBefore(slider, img);
position the slider in the middle:*/
slider.style.top = (h / 2) - (slider.offsetHeight / 2) + "px";
slider.style.left = (w / 2) - (slider.offsetWidth / 2) + "px";
Enter fullscreen mode Exit fullscreen mode

Now, Let us add the listeners that will be triggered when we press the mouse button.

/*execute a function when the mouse button is pressed:*/
slider.addEventListener("mousedown", slideReady);
/*and another function when the mouse button is released:*/
window.addEventListener("mouseup", slideFinish);    
/*or touched (for touch screens:*/
slider.addEventListener("touchstart", slideReady);
/*and released (for touch screens:*/
window.addEventListener("touchstop", slideFinish);
Enter fullscreen mode Exit fullscreen mode

Now, Basic structure of our slider is created. Next we need to create some functions that will perform the main functionality of the slider. i.e, Slide over the the image.

For this we will first create slideReady Function inside the compareImages Function that will be executed when mouse button is pressed.

function slideReady(e) {
    /*prevent any other actions that may occur when moving over the image:*/
    e.preventDefault();
    /*the slider is now clicked and ready to move:*/
    clicked = 1;
    /*execute a function when the slider is moved:*/
    window.addEventListener("mousemove", slideMove);
    window.addEventListener("touchmove", slideMove);
}
Enter fullscreen mode Exit fullscreen mode

Next, create another Function inside the compareImages Function when the slider is no longer clicked

function slideFinish() {
    /*the slider is no longer clicked:*/
    clicked = 0;
}
Enter fullscreen mode Exit fullscreen mode

Now, we will create 3 more functions in compareImages with which we will get the cursor position and move the slider accordingly across the Image window

function slideMove(e) {
    var pos;
    /*if the slider is no longer clicked, exit this function:*/
    if (clicked == 0) return false;
    /*get the cursor's x position:*/
    pos = getCursorPos(e)
        /*prevent the slider from being positioned outside the image:*/
    if (pos < 0) pos = 0;
    if (pos > w) pos = w;
    /*execute a function that will resize the overlay image according to the cursor:*/
    slide(pos);
}

function getCursorPos(e) {
    var a, x = 0;
    e = e || window.event;
    /*get the x positions of the image:*/
    a = img.getBoundingClientRect();
    /*calculate the cursor's x coordinate, relative to the image:*/
    x = e.pageX - a.left;
    /*consider any page scrolling:*/
    x = x - window.pageXOffset;
    return x;
}

function slide(x) {
    /*resize the image:*/
    img.style.width = x + "px";
    /*position the slider:*/
    slider.style.left = img.offsetWidth - (slider.offsetWidth / 2) + "px";
}
Enter fullscreen mode Exit fullscreen mode

Wrap it all in a parent function with name initComparisons.
Now we have covered all the aspects of this now let's see the full Scripts.js file

function initComparisons() {
    var x, i;
    /*find all elements with an "overlay" class:*/
    x = document.getElementsByClassName("img-comp-overlay");
    for (i = 0; i < x.length; i++) {
        /*once for each "overlay" element:
        pass the "overlay" element as a parameter when executing the compareImages function:*/
        compareImages(x[i]);
    }

    function compareImages(img) {
        var slider, img, clicked = 0,
            w, h;
        /*get the width and height of the img element*/
        w = img.offsetWidth;
        h = img.offsetHeight;
        /*set the width of the img element to 50%:*/
        img.style.width = (w / 2) + "px";
        /*create slider:*/
        slider = document.createElement("DIV");
        slider.setAttribute("class", "img-comp-slider");
        /*insert slider*/
        img.parentElement.insertBefore(slider, img);
        /*position the slider in the middle:*/
        slider.style.top = (h / 2) - (slider.offsetHeight / 2) + "px";
        slider.style.left = (w / 2) - (slider.offsetWidth / 2) + "px";
        /*execute a function when the mouse button is pressed:*/
        slider.addEventListener("mousedown", slideReady);
        /*and another function when the mouse button is released:*/
        window.addEventListener("mouseup", slideFinish);
        /*or touched (for touch screens:*/
        slider.addEventListener("touchstart", slideReady);
        /*and released (for touch screens:*/
        window.addEventListener("touchstop", slideFinish);

        function slideReady(e) {
            /*prevent any other actions that may occur when moving over the image:*/
            e.preventDefault();
            /*the slider is now clicked and ready to move:*/
            clicked = 1;
            /*execute a function when the slider is moved:*/
            window.addEventListener("mousemove", slideMove);
            window.addEventListener("touchmove", slideMove);
        }

        function slideFinish() {
            /*the slider is no longer clicked:*/
            clicked = 0;
        }

        function slideMove(e) {
            var pos;
            /*if the slider is no longer clicked, exit this function:*/
            if (clicked == 0) return false;
            /*get the cursor's x position:*/
            pos = getCursorPos(e)
                /*prevent the slider from being positioned outside the image:*/
            if (pos < 0) pos = 0;
            if (pos > w) pos = w;
            /*execute a function that will resize the overlay image according to the cursor:*/
            slide(pos);
        }

        function getCursorPos(e) {
            var a, x = 0;
            e = e || window.event;
            /*get the x positions of the image:*/
            a = img.getBoundingClientRect();
            /*calculate the cursor's x coordinate, relative to the image:*/
            x = e.pageX - a.left;
            /*consider any page scrolling:*/
            x = x - window.pageXOffset;
            return x;
        }

        function slide(x) {
            /*resize the image:*/
            img.style.width = x + "px";
            /*position the slider:*/
            slider.style.left = img.offsetWidth - (slider.offsetWidth / 2) + "px";
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Now the final step, use this script in HTML and call the initComparisons function at the starting of the page where you want the slider.

<script>
    initComparisons();
</script>
Enter fullscreen mode Exit fullscreen mode

The final product will look like:-
Image description

Wrapping Up

I hope you enjoyed the article, if yes then don't forget to press ❤️. You can also bookmark it for later use. It was fun to make this slider and If you have any queries or suggestions don't hesitate to drop them. See you.

💖 💪 🙅 🚩
anomaly3108
anomaly3108

Posted on January 1, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related