vsdrug
Last Updated: November 14, 2018
·
385.1K
· guangyi

How to create an image slider with javascript

There are many image sliders on the internet. Most of then are written by jQuery. I just want to learn JS and get a better understanding of it, so i use javascript to complete it.

you can find the demo here:

1.basic:http://cssdeck.com/labs/image-slider-1

2.with prev/next button: http://cssdeck.com/labs/imageslider-button

3.with pager: http://cssdeck.com/labs/imageslider-pager

Demo 1 is different from demo 2 and 3; and demo 2 and 3 are using the same core codes.

Below is how to do the basic one—move to the next image after a set of time interval. no user interrupt.

The basic idea of image slider is to create a long list. actually is a long 'ul'

The html part is:

<div class=”container”>
    <div class=”image-slider-wrapper”>
        <ul id=”image_slider”>
            <li><img src=”./image/1.jpg”></li>
            <li><img src=”./image/4.jpg”></li>
            <li><img src=”./image/5.jpg”></li>
            <li><img src=”./image/4.jpg”></li>
            <li><img src=”./image/1.jpg”></li>
            <li><img src=”./image/5.jpg”></li>
        </ul> 
    </div>
</div>

the image-slider-wrapper part is for the convenience when I do future work.

the css part is:

.container{
    width:800px;
    height:400px;
    padding:20px;
    border:1px solid gray;
    -webkit-box-sizing:border-box;
    -moz-box-sizing:border-box;
    box-sizing:border-box;
    background: black; 
}
.image-slider-wrapper{
    overflow: hidden;
}
#image_slider{
    position: relative;
    height: 280px;
    padding:0;
}
#image_slider li{
    max-width: 100%;
    float:left;
    list-style: none;
}

The image-slider-wrapper need to set overflow: hidden cause ul will be a very long list in a line. but only one image can be seen.

There are no width set for ul( id=image_slider) because we will set it in Javascript. So when there are more/less images we don’t need to change css.

Webkit has default padding and margin for ul, so we will initialize it with 0px.

Set li to list-style:none and float left, so the images will be in a long line.

All right, now we’ve have everything ready to move.

Next is the JS part.
In the function init(), 1. set ul width 2. move ul

var ul;
var liItems; 
var imageWidth;
var imageNumber;

function init(){

    ul = document.getElementById(‘image_slider’);
    liItems = ul.children;
    imageNumber = liItems.length;
    imageWidth = liItems[0].children[0].offsetWidth;
    // set ul’s width as the total width of all images in image slider.
    ul.style.width = parseInt(imageWidth * imageNumber) + ‘px’;
    slider(ul);
}

.offsetWidht returns a number! (typeof(imageWidth) returns “number”).

offsetWidth is the width that includes content, padding, scrollbar and border.if there are borders for each image, the width of ul will also be correct.

we can also use computedStyle to get the width of one image, but in that case what we get is “760px”, not 760

var computedStyle = document.defaultView.getComputedStyle(liItems[i].childNodes[0], null);
imageWidth = computedStyle.width;

here is the function slider()

/**delta function is to set how the image slide—keep still for a while and move to next picture.
*step function will be called many times until clearInterval() been called
* currentImage * imageWidth is the currentImage position of ul
* delta start from 0 to 1, delta * imageWidth is the pixels that changes
**/
 function slider(ul){ 
    animate({
        delay:17,
        duration: 3000,
        delta:function(p){return Math.max(0, -1 + 2 * p)},
        step:function(delta){
            ul.style.left = ‘-’ + parseInt(currentImage * imageWidth + delta * imageWidth) + ‘px’;
    },
        callback:function(){
            currentImage++;
        // if it doesn’t slied to the last image, keep sliding
            if(currentImage < imageNumber-1){
                slider(ul);
        }
       // if current image it’s the last one, it slides back to the first one
            else{
                var leftPosition = (imageNumber - 1) * imageWidth;
               // after 2 seconds, call the goBack function to slide to the first image 
                setTimeout(function(){goBack(leftPosition)},2000); 
                setTimeout(function(){slider(ul)}, 4000);
            }
        }
    });
}

The delta function make sure that each animation will keep still for a while then move to the next image. (if y<0, then y=0;)

The step function does the animation. But it only slide one image. The callback function will make sure there is a loop for all images. And if it’s the last image, it calls the “goBack” function to slide to the first image.

function goBack(leftPosition){
    currentImage = 0; 
    var id = setInterval(function(){
        if(leftPosition >= 0){
            ul.style.left = ‘-’ + parseInt(leftPosition) + ‘px’;
            leftPosition -= imageWidth / 10;
        }
        else{
            clearInterval(id);
        } 
    }, 17);
}

Here is the generic animation function I learned form the javascript animation tutorial i posted the link below. The only difference is after clearInterval() i will call the callback function to keep the animation loop going on.

The animate function is a generic function from this article:

I think it’s a pretty good one.

http://javascript.info/tutorial/animation#the-generic-animation

//generic animate function
function animate(opts){
    var start = new Date;
    var id = setInterval(function(){
        var timePassed = new Date - start;
        var progress = timePassed / opts.duration
        if(progress > 1){
            progress = 1;
        }
        var delta = opts.delta(progress);
        opts.step(delta);
        if (progress == 1){
            clearInterval(id);
           opts.callback();
         }
    }, opts.dalay || 17);
}
window.onload = init;

WIth the window.inload = init; as the end, the image slider has been successfully finished!

I know there are many places to improve, for example this one is not a responsive one, also the architecture may has problems too. I'm learning new thing everyday.I will keep practicing and write better code!

周周加油!

15 Responses
Add your response

15490

where is currentImage defined? :)

over 1 year ago ·
15888

thx u alot

over 1 year ago ·
15889

thx u alot

over 1 year ago ·
17277

Thank you very very much. I've used it into a webpage I'm developing at this moment. How would you like to be referred? Would be enough in code comments?

over 1 year ago ·
18038

verynice tutorial. cleared a lot concepts related with this
@ http://html5beginners.com

over 1 year ago ·
23090

its great

over 1 year ago ·
27518

it isn't work for me :( I'll figure out :)

over 1 year ago ·
28609

the animate function doesn't work

over 1 year ago ·
28902

thank your for this slider but there are many free sliders available today.

over 1 year ago ·
29894

Thanks for sharing this helpful and easy-to-understand guide
http://shellshocker-io.com

6 months ago ·
29931

There are many image sliders on the internet. Most of then are written by jQuery. I just want to learn JS and get a better understanding of it, so i use javascript to complete it.
Mobdro Apk download is the rebel in the field of video streaming apps. Mobdro understands the basic need of the consumer. It provides the user with a large collection of videos, shows and movies.
https://7downloads.com/download-mobdro-for-pc-windows-10-8-7-laptop

6 months ago ·
30284

It obtained 3 stars in respect of https://bestdishwashertool.jimdosite.com/ worth for cash and also quietness.Like Miele, http://bestdishwasherrange.wikidot.com/ Bosch is one more German device supplier http://dishwasherupgrad.strikingly.com/ with a large series of dishwashers. http://bestdishwashermanual.webstarts.com/ Several are still made in Germany, but others http://shopbestdishwasher.doodlekit.com/ are made in other European nations.

3 months ago ·
30645

There are 12 various tips that could https://topwaterflosserguide.puzl.com/ be made use of for all kinds of https://sterlinewaterflosser.sitey.me/ purposes 4 jet ideas, 2 gum suggestions

2 months ago ·
31208

Step 1

Create a folder named “images” in the project path and put all the images required for the slider. Make sure that all the images are in same size (width*height). Otherwise, the slider will misbehave while navigating between slides.

Step 2

Add the below code in body section of the HTML page.

<body>

<div class="slidercontainer">

<div class="showSlide fade">



<div class="content">Lorem ipsum dolor sit amet</div>

</div>

<div class="showSlide fade">



<div class="content">Lorem ipsum dolor sit amet</div>

</div>

    <div class="showSlide fade">  
        <img src="images/img3.jpg"/>  
        <div class="content">Lorem ipsum dolor sit amet</div>  
    </div>  
    <div class="showSlide fade">  
        <img src="images/img4.jpg"/>  
        <div class="content">Lorem ipsum dolor sit amet</div>  
    </div>  
    <!-- Navigation arrows -->  
    <a class="left" onclick="nextSlide(-1)">❮</a>  
    <a class="right" onclick="nextSlide(1)">❯</a>  
</div>  

</body>

Here, <div class="slidercontainer"> is the main container for slider and <div class="showSlide fade"> are the slider images section that are repeating.

Step 3

Write the JavaScript code. Considering it a small example, I am writing the code in the same HTML page using <script type="text/javascript"></script>.

If required, you can create an external JS file in the project path and refer it to the HTML page.
<script type="text/javascript">

var slideindex = 1;

displaySlides(slide
index);

function nextSlide(n) {

displaySlides(slideindex += n);

}

function currentSlide(n) {

displaySlides(slide
index = n);

}

function displaySlides(n) {

var i;

var slides = document.getElementsByClassName("showSlide");

if (n > slides.length) { slideindex = 1 }

if (n < 1) { slide
index = slides.length }

for (i = 0; i < slides.length; i++) {

slides[i].style.display = "none";

}

slides[slide_index - 1].style.display = "block";

}

</script>

All the above functions are user defined. We just only write some logic to read the slides and showing.

Step 4

Now, it's time to apply CSS to showcase the images in a proper position with some styles. Below is the final code --

HTML+JavaScript+CSS,
<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<title>My Slider</title>

<style type="text/css">

body {

margin: 0;

background: #e6e6e6;

}

.showSlide {

display: none

}

.showSlide img {

width: 100%;

}

.slidercontainer {

max-width: 1000px;

position: relative;

margin: auto;

}

.left, .right {

cursor: pointer;

position: absolute;

top: 50%;

width: auto;

padding: 16px;

margin-top: -22px;

color: white;

font-weight: bold;

font-size: 18px;

transition: 0.6s ease;

border-radius: 0 3px 3px 0;

}

.right {

right: 0;

border-radius: 3px 0 0 3px;

}

.left:hover, .right:hover {

background-color: rgba(115, 115, 115, 0.8);

}

.content {

color: #eff5d4;

font-size: 30px;

padding: 8px 12px;

position: absolute;

top: 10px;

width: 100%;

text-align: center;

}

.active {

background-color: #717171;

}

/* Fading animation */

.fade {

-webkit-animation-name: fade;

-webkit-animation-duration: 1.5s;

animation-name: fade;

animation-duration: 1.5s;

}

@-webkit-keyframes fade {

from {

opacity: .4

}

to {

opacity: 1

}

}

    @keyframes fade {  
        from {  
            opacity: .4  
        }  
        to {  
            opacity: 1  
        }  
    }  
</style>  

</head>

<body>

<div class="slidercontainer">

<div class="showSlide fade">



<div class="content">Slide1 heading</div>

</div>

<div class="showSlide fade">



<div class="content">Slide2 heading</div>

</div>

    <div class="showSlide fade">  
        <img src="images/img3.jpg" />  
        <div class="content">Slide3 heading</div>  
    </div>  
    <div class="showSlide fade">  
        <img src="images/img4.jpg" />  
        <div class="content">Slide4 heading</div>  
    </div>  
    <!-- Navigation arrows -->  
    <a class="left" onclick="nextSlide(-1)">❮</a>  
    <a class="right" onclick="nextSlide(1)">❯</a>  
</div>  

<script type="text/javascript">  
    var slide_index = 1;  
    displaySlides(slide_index);  

    function nextSlide(n) {  
        displaySlides(slide_index += n);  
    }  

    function currentSlide(n) {  
        displaySlides(slide_index = n);  
    }  

    function displaySlides(n) {  
        var i;  
        var slides = document.getElementsByClassName("showSlide");  
        if (n > slides.length) { slide_index = 1 }  
        if (n < 1) { slide_index = slides.length }  
        for (i = 0; i < slides.length; i++) {  
            slides[i].style.display = "none";  
        }  
        slides[slide_index - 1].style.display = "block";  
    }  
</script>  

</body>

</html>

If you notice in the above code, I haven’t included any libraries, not even jQuery.

Step 5

Now, let's run the HTML page in browser and see the output. The slider should work properly.

Thanks for reading this article. Hope it helps.

3 days ago ·
31242

This is very useful information for me. Thank you very much!

1 day ago ·