vikas sajwan
vikas sajwan

Reputation: 31

how to implement automatic sliding images through array in javascript

I want to implement sliding images as soon as the website loads.

Here's my html code

<html>
<title>Wold of Guitars</title>
<body onload="images()">
</body>
</html>

And here's my javascript

var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = '../img/n/h1.jpg';
imgArray[1] = new Image();
imgArray[1].src = '../img/n/h2.jpg';
imgArray[2] = new Image();
imgArray[2].src = '../img/n/home.jpg';
imgArray[3] = new Image();
imgArray[3].src = '../img/n/h3.jpg';
imgArray[4] = new Image();
imgArray[4].src = '../img/n/h4.jpg';
x=-1;
function images()
{    x=x+1
     if(x>4)
     x=1
     document.write("<li><img src='" + imgArray[x] + "' width="1350" height="630"/><span>" + imgArray[] + "</span></li>");
     var t=setInterval("images()",3000);
}

Help will be appreciated.

Upvotes: 0

Views: 16684

Answers (1)

maximumcallstack
maximumcallstack

Reputation: 2917

Although you mentioned "sliding" your initial code looked liked you wanted to swap the images over time.

I admit you may struggle to find good resources on JavaScript for something so simple, which Is why I can relate to your question.

Ok so here's a quick & dirty but more modern-ish image changing slide requestAnimationFrame:

https://jsfiddle.net/julienetienne/95tqftnk/4/

The same principals apply for making images slide except you are pre-loading all images and shifting the position by the slide show width.

var speed = 3;

// Your image array
var images = [
    'http://www.gettyimages.co.uk/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg',
    'http://www.hdwallpapersimages.com/wp-content/uploads/images/Child-Girl-with-Sunflowers-Images.jpg',
    'http://www.gettyimages.co.uk/CMS/StaticContent/1391099215267_hero2.jpg'];

// Get the slideShow tag
var slideShow = document.getElementById('slide-show');

// Create the image tag  //You could also just make one in HTML and get the tag
var img = document.createElement('img');

// Append the image to the slideshow container
slideShow.appendChild(img);

// Basic request animation polyfill 
var rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
        return setTimeout(callback, 1000 / 60);
    };

// declare var count outside of rAF loop
var count;

function changeImage(timeStamp) {
    count = Math.floor(timeStamp / 1000 / speed);

while (count > images.length -1) {
    count -= images.length;
}

    img.src = images[count];

    rAF(changeImage);
}

rAF(changeImage);
img {
    width: 600px;
    height auto;
}
<div id="slide-show"></div>

Upvotes: 1

Related Questions