I'm trying to create a very simple piece of code that allows you to move a red and blue ball around the screen - you click on the one you want to move then use the arrow keys. The part I'm struggling with is changing which ball is focused on, ie moved when you press the arrow keys.
The plan is to add a .active class to ball you click on, while also removing the active class from the other.
I've got two simple divs, with the blue div initially set with the .active class:
<div id="blue" class="active"></div>
<div id="red"></div>
Here's the CSS:
div {
height: 100px;
width: 100px;
border-radius: 50%;
border: 5px solid gray;
margin: 20px;
position: relative;
}
#blue {
background-color: blue;
}
#red {
background-color: red;
}
Here's my javascript:
$(document).ready(function() {
$("body").keydown(function(key) {
switch(parseInt(key.which,10)) {
// Left arrow key pressed
case 37:
$('.active').animate({left: "-=10px"}, 1);
break;
// Up Arrow Pressed
case 38:
case 37:
$('.active').animate({top: "-=10px"}, 1);
break;
// Right Arrow Pressed
case 39:
case 37:
$('.active').animate({left: "+=10px"}, 1);
break;
// Down Array Pressed
case 40:
case 37:
$('.active').animate({top: "+=10px"}, 1);
break;
}
});
});
$(document).on("click", "#red", function () {
$("#red").addClass(".active");
$("#blue").removeClass(".active");
});
$(document).on("click", "#blue", function () {
$("#blue").addClass(".active");
$("#red").removeClass(".active");
});
I can move the blue ball around but clicking the red has no effect, the arrow keys continue to move the blue div.
Here it is on jsfiddle - http://jsfiddle.net/7NF3L/
Any suggestions as to better ways to achieve the same thing would also be welcome.