Basically, each branch of your if/else does the following:
- Update the appropriate
shipXXX
variable with an appropriate increment. - Set the appropriate
ship.style.xxx
value. - Call
changeColor()
. - return the newly modified value.
The last three steps are pretty much the same for all branches once you have the value and know the style name. So, you can move those three steps to a common place and do them once and just set up the appropriate state in the if/else.
Also, this structure:
(e.keyCode === 37)||(e === 37)
Is repeated each time. Since there can't be a case where e
is an object that has a .KeyCode
property and where e ==== 37
, then you can figure out once before all the comparisons whether there is a .KeyCode
property or not and just use that knowledge. This also simplifies the comparisons.
I'm also assuming that the variable y
in your code is just something you are temporarily using and not something you're really trying to set (it appears to be an accidental global and is not being used elsewhere so I've removed it).
You can extract out some of the repeated code like this:
function anim(e) { var direction, val, key = e.KeyCode || e; if (key === 37) { direction = "left"; shipLeft -= 11; val = shipLeft; } else if (key === 39) { direction = "left"; shipLeft += 11; val = shipLeft; } else if (key === 40) { direction = "top"; shipTop += 11; val = shipTop; } else if (key === 38) { direction = "top"; shipTop -= 11; val = shipTop; } else { return; } ship.style[direction] = val +'px'; changeColor(); return val;}