Skip to content

Instantly share code, notes, and snippets.

@jonurry
Created March 26, 2018 11:19
Show Gist options
  • Save jonurry/b404965aecbbeef00b44449707917f8d to your computer and use it in GitHub Desktop.
Save jonurry/b404965aecbbeef00b44449707917f8d to your computer and use it in GitHub Desktop.
15.1 Baloon (Eloquent JavaScript Solutions)
<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>
@jonurry
Copy link
Author

jonurry commented Mar 26, 2018

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