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> |
Hints
You’ll want to register a handler for the "keydown
" event and look at event.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 the textContent
property of its parent node to a new string.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Handling Events
15.1 Balloon
Write a page that displays a balloon (using the balloon emoji). When you press the up arrow, it should inflate (grow) ten percent, and when you press the down arrow, it should deflate (shrink) 10%.
You can control the size of text (emoji are text) by setting the
font-size
CSS property (style.fontSize
) on its parent element. Remember to include a unit in the value, for example, pixels (10px
).The key names of the arrow keys are "
ArrowUp
" and "ArrowDown
". Make sure the keys only change the balloon, without scrolling the page.When that works, add a feature where, if you blow up the balloon past a certain size, it explodes. In this case, exploding means that it is replaced with a bang emoji, and the event handler is removed (so that you can’t inflate or deflate the explosion).