Skip to content

Instantly share code, notes, and snippets.

@galvez
Last active June 24, 2017 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save galvez/6e25796f429f022dbabd634c576c2394 to your computer and use it in GitHub Desktop.
Save galvez/6e25796f429f022dbabd634c576c2394 to your computer and use it in GitHub Desktop.
<style>
.cobra {
position: absolute;
top: 100px;
left: 100px;
width: 200px;
height: 20px;
background: #ccc;
border-radius: 10px;
}
</style>
<div class="cobra">
</div>
<script>
let left = 100
const cobra = document.querySelector('.cobra')
let mover = null
let speed = 5
window.addEventListener('keydown', (e) => {
if (e.key === ' ') {
speed = 10
} else if (['ArrowRight', 'ArrowLeft'].includes(e.key)) {
if (mover === null) {
mover = setInterval(() => {
left += {'ArrowRight': speed, 'ArrowLeft': speed * -1}[e.key]
cobra.style.left = left + "px"
}, 80)
}
}
})
window.addEventListener('keyup', (e) => {
if (speed == 10) {
speed = 5
} else {
clearInterval(mover)
mover = null
}
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment