Pitch your project

Random text






Blogs

0    
By admin Category Uncategorized, Posted March 16th, 2016
How to make an onClick image slider in JavaScript

Hi there,
First of all the image slider which we are going to make make is basically changing the image source when you click on a button “image”. So I’ll give you an example of the image slider so you know what to expect.

Example

See the Pen bpbBqG by Danny (@DannySuijker) on CodePen.

Code

First of all we will make a HTML file named index.html and add the following code inside the file.

< !DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
    <div class="slider">
        <img id="left-button" onclick="onClick('left')" src="image/left.png"/>
        <img id="right-button" onclick="onClick('right')" src="image/right.png"/>
        <img class="Image" src="image/forest.jpg"/>
    </div>
</body>
</html>

The left and the right buttons are pictures that are located in the image folder.

Now we need to style the page so lets make a CSS file name it style.css and fill it with the following code.

.slider {
    display: inline-block;
    position: relative;
}
​
#left-button {
    z-index: 9;
    left: 5px;
    margin-top: 30%;
    max-width: 25px;
    width: 100%;
    height: auto;
    position: absolute;
}
​
#right-button {
    z-index: 9;
    right: 5px;
    margin-top: 30%;
    max-width: 25px;
    width: 100%;
    height: auto;
    position: absolute;
}
.image {
    width: 800px;
    height: 500px;
}

So now we have styled our page it’s time to put in the functionality. to do this make a JavaScript file named imageslider.js and put the following code in it.

var picture = [image/forest.jpg,image/mountain.jpg,image/sao-paulo.jpg];
var index = 0;
​
function onClick(direction) {
    if(direction === 'left') {
​
        if(index !== 0) {
            index--;
            var source = picture[index];
            document.getElementsByClassName('image')[0].src = source;
        }
        else {
            index = picture.length-1;
            var source = picture[index];
            document.getElementsByClassName('image')[0].src = source;
        }
    }
    else {
        if(index !== picture.length-1) {
            index++;
            var source = picture[index];
            document.getElementsByClassName('image')[0].src = source;
        }
        else {
            index = 0;
            var source = picture[index];
            document.getElementsByClassName('image')[0].src = source;
        }
    }
}

Congratulations now you have learned how to make your own image slider. Get the files at my GitHub

Posted by Danny Suijker

Leave a Reply

Your email address will not be published. Required fields are marked *