Question

I've come up with this little animation that uses images in an array, but it's sloppy. What I'd really like is to modularize it so that I can use multiple instances of the same function to animate different arrays depending on which key is pressed. Also, I'd like to get it so that the animation stops when the key is released, if possible. I realize that calling all of those variables globally is a big no-no, but I have no idea how to make it work otherwise! Last but not least, I'd like to figure out how to get that last bit of inline script over to the external file and have it still work correctly. Any help would be much appreciated! But please note, I'm a novice with JavaScript, so please try to be as specific/detailed as possible so I can learn from your wisdom! Thank you!

I've created a jsfiddle.

HTML:

<div id="wrapper">
<span id="jajo"><img id="my_img" src="jajo.png" /></span>
<script>element = document.getElementById("jajo"); </script>
</div><!--wrapper-->

JavaScript:

var i = 0;
var element;
var waveArray = ["wave0.png","wave1.png","wave2.png","wave3.png","wave4.png","wave5.png"];
var jumpArray = ["jump0.png","jump1.png","jump2.png","jump3.png","jump4.png","jump5.png"];
var foodArray = ["food0.png","food1.png","food2.png","food3.png","food4.png","food5.png"];

document.onkeydown = function(event) {
var keyPress = String.fromCharCode(event.keyCode);

if(keyPress == "W") { // if "w" is pressed, display wave animation
    increment ();

    document.onkeyup = function(event) { // if "w" is released, display default image
        document.getElementById("jajo").innerHTML= "<img alt='Jajo' src='jajo.png'>";
    }
} else if(keyPress == "A") { // if "a" is pressed, display jump animation
} else if(keyPress == "S") { // if "s" is pressed, display food animation
}
}

function increment (){
i++;
if(i > (waveArray.length - 1)){
    i = 0;
}
setTimeout(animation,1000/30);
}


function animation() {
var img = '<img src="' + waveArray[i] + '" alt="Jajo" />';
element.innerHTML = img;
setTimeout(increment, 2000/30);
}
Was it helpful?

Solution

Demo

http://jsfiddle.net/ghQwF/4/

Module

var animation = (function() {
    var delay = 1000 / 30;
    var map = {}, active = [], timer;
    function animate() {
        for(var i=0, l=active.length; i<l; ++i) {
            var data = map[active[i]];
            ++data.index;
            data.index %= data.array.length;
            data.image.src = data.array[data.index];
        }
        timer = setTimeout(animate, delay);
    }
    function begin(e) {
        var key = String.fromCharCode(e.keyCode),
            data = map[key];
        if(!data) return;
        if(!active.length) timer = setTimeout(animate, delay);
        if(!~active.indexOf(key)) active.push(key);
    }
    function end(e) {
        var key = String.fromCharCode(e.keyCode),
            data = map[key];
        if(!data) return;
        data.image.src = data.default;
        var index = active.indexOf(key);
        if(!~index) return;        
        active.splice(index, 1);
        if(!active.length) clearTimeout(timer);
    }
    return {
        add: function(data) {
            data.index = data.index || 0;
            data.image = data.image || data.target.getElementsByTagName('img')[0];
            data.default = data.default || data.image.src;
            map[data.key] = data;
        },
        remove: function(key) {
            delete map[key];
        },
        enable: function() {
            document.addEventListener('keydown', begin, false);
            document.addEventListener('keyup', end, false);
        },
        disable: function() {
            document.removeEventListener('keydown', begin, false);
            document.removeEventListener('keyup', end, false);
            clearTimeout(timer);
            active = [];
        }
    };
})();

Example

animation.enable();
animation.add({
    key: 'W',
    target: document.getElementById('jajo'),
    array: [
        "http://static.spoonful.com/sites/default/files/styles/square_128x128/public/crafts/fingerprint-flowers-spring-craft-photo-420x420-aformaro-01.jpg",
        "http://static.spoonful.com/sites/default/files/styles/square_128x128/public/crafts/paper-flowers-spring-craft-photo-420x420-aformaro-11.jpg",
        "http://static.spoonful.com/sites/default/files/styles/square_128x128/public/crafts/tissue-paper-flowers-kaboose-craft-photo-350-fs-IMG_8971_rdax_65.jpg"
    ]
});
animation.add({ /* ... */ });

Methods

add

Adds a new animation, with parameters:

  • key: key to activate animation
  • target: wrapper of the image (optional if image is specified)
  • image: image to animate (optional, defaults to first image in target)
  • default: default url of the image (optional, defaults to original url)
  • index: initial position in array (optional, defaults to 0)
  • array: array of images

remove

Removes the animation related with key specified.

disable

Disables animations (typing keys would have no effect), and stops current ones.

enable

Enable animations (typing keys can start animations).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top