Week 9 Section 8
Event handling with ninjas
by jazahn
HTML
<div id="container">
</div>
CSS
#container{
height: 200px;
width: 400px;
border: 1px solid black;
background-color: #dddddd;
position: relative;
}
.ninjaRight {
/* 22 across, 4 down : img is 920x160 : 40px high and 40px across */
background: url(http://stuff.thoughtbox.at/lastninja/images/ninja_sprite.png) 0 0;
}
.ninjaLeft {
background: url(http://stuff.thoughtbox.at/lastninja/images/ninja_sprite.png) 0 80px;
}
.ninja {
height: 40px;
width: 40px;
position:absolute;
}
JavaScript
var Ninja = function(config){
this.config = config || {};
this.top = this.config.top || 90;
this.left = this.config.left || 190;
this.keyCodes = {
37: this.goLeft,
38: this.goUp,
39: this.goRight,
40: this.goDown
};
this.create();
this.listen();
};
Ninja.prototype.create = function(){
this.div = document.createElement("div");
this.div.id = this.config.id;
this.div.className = "ninja ninjaRight";
this.div.style.top = this.top + "px";
this.div.style.left = this.left + "px";
var container = document.getElementById("container");
container.appendChild(this.div);
};
Ninja.prototype.listen = function(){
var that = this;
this.moveListener = document.addEventListener("keyup", function(event){
that.keyCodes[event.keyCode].call(that);
});
};
Ninja.prototype.goLeft = function(){
this.left -= this.config.step;
this.div.style.left = this.left + "px";
this.div.className = "ninja ninjaLeft";
};
Ninja.prototype.goUp = function(){
this.top -= this.config.step;
this.div.style.top = this.top + "px";
};
Ninja.prototype.goRight = function(){
this.left += this.config.step;
this.div.style.left = this.left + "px";
this.div.className = "ninja ninjaRight";
};
Ninja.prototype.goDown = function(){
this.top += this.config.step;
this.div.style.top = this.top + "px";
};
var ninja = new Ninja({
name: "unimportant",
top: 90,
left: 190,
step: 20,
id: "ninja1"
});