Created
March 26, 2018 11:19
-
-
Save jonurry/b404965aecbbeef00b44449707917f8d to your computer and use it in GitHub Desktop.
15.1 Baloon (Eloquent JavaScript Solutions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<p>🎈</p> | |
<script> | |
let baloon = document.querySelector('p'); | |
let fontSize = 16; | |
let fontUnit = 'px'; | |
function increaseFontSizeOfElement(node, percentage) { | |
fontSize += fontSize * percentage; | |
node.style.fontSize = fontSize + fontUnit; | |
}; | |
function listenForArrowUpDown(e) { | |
if (e.key == 'ArrowUp') { | |
increaseFontSizeOfElement(baloon, 0.1); | |
e.preventDefault(); | |
} else if (e.key == 'ArrowDown') { | |
increaseFontSizeOfElement(baloon, -0.1); | |
e.preventDefault(); | |
} | |
if (fontSize > 100) { | |
baloon.textContent = '💥'; | |
document.removeEventListener('keydown', listenForArrowUpDown); | |
} | |
}; | |
increaseFontSizeOfElement(baloon, 0); | |
document.addEventListener('keydown', listenForArrowUpDown); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hints
You’ll want to register a handler for the "
keydown
" event and look atevent.key
to figure out whether the up or down arrow key was pressed.The current size can be kept in a binding, so that you can base the new size on it. It’ll be helpful to define a function that updates the size—both the binding and the style of the balloon in the DOM, so that you can call it from your event handler, and possibly also once when starting, to set the initial size.
You can change the balloon to an explosion by replacing the text node with another one (using
replaceChild
), or by setting thetextContent
property of its parent node to a new string.