Startec
Startec

Reputation: 13206

How to load an initial set of images, then animate between them randomly without jQuery

On my page I have a gallery (just a div) with several images on it. I want to show the first 9 images immediately, then load more images and use CSS transitions to animate between the existing images.

Loading the initial images is easy but I do not know the best way to load the next set of images and then start animating (using the CSS Transform property). So far this is what I have:

HTML (abbreviated):

<div id="mainContainer">
    <div class="imageHolder"><img class="homeImages" src="test.png"></div>
    <div class="imageHolder"><img class="homeImages" src="test1.png"></div>
    <div class="imageHolder"><img class="homeImages" src="test3.png"></div>
</div>

CSS (abbreviated):

img {
    display: inline;
    position: relative;
    margin: 0;
    padding: 0;
    width: 30%;
}

.changed.opaque {
    opacity: 0;
    border: 2px solid red;
}

I am looking to do a variety of effects, the most simple one would be to change the opacity and fade one image over the other. To load the next set of images I have this:

Javascript:

    var imageArray = [
        'test2.png',
        'test3.png',
        'test4.png',
        'test5.png',
        'test6.png',
    ];
    var imageNodeArray = [];

    for(var i = imageArray.length - 1; i >= 0; i -= 1) {
        var img = new Image();
        img.onload = function() {
           imageNodeArray.push(this);
        };
        img.src = imageArray[i];
    }
    document.onclick = function() {
        imageNodeArray[0].setAttribute('class', 'changed.opaque');
        divs[0].appendChild(imageNodeArray[0])
    }

This does add an image to my mainContainer however, even though I can tell from devTools that it has the changed.opaque class applied to it, no opacity is shown on the added image.

I am curious about this. I would also like to know the best way to "stack" images to have a bunch to animate through. I am not sure that appending child is right.... Thank you

Upvotes: 2

Views: 179

Answers (1)

Rich Flavell
Rich Flavell

Reputation: 436

function animate() {
    var index = Math.floor((Math.random() * document.querySelectorAll('#mainContainer > .imageHolder').length + 1));
    var current = document.querySelector('.top');
    var next = document.querySelector('.imageHolder:nth-of-type(' + index + ')');
    current.className = "imageHolder";
    next.className += "top";
}

Should be able to handle and switch between any dynamically inserted images.

Currently using:

.imageHolder {
    display: none;
}
.top {
    display: inherit;
}

to switch the image is just a simple implementation.

Here's the working fiddle: http://jsfiddle.net/e9dxN/1/

Alternative implementation: http://jsfiddle.net/e9dxN/6/

Upvotes: 2

Related Questions