The code below asks the user how many eggs they would like, ensures they enter a value, and renders a number of egg images matching the entered value.
Update this code to ask the user how many dozens of eggs they would like, and render the one-dozen.gif
image instead.
Last active
August 29, 2015 14:16
-
-
Save johntron/60286857300172667926 to your computer and use it in GitHub Desktop.
This file contains 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
How many eggs would you like: <input> <span></span><br /> | |
<script src="main.js"></script> |
This file contains 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
document.querySelector('input').onkeyup = function (e) { | |
e.preventDefault(); | |
var val = e.target.value; | |
if (!is_valid(val)) { | |
show_error('Please enter a number'); | |
return; | |
} | |
hide_error(); | |
save(val); | |
}; | |
function is_valid (val) { | |
if (val.length > 0) { | |
return true; | |
} | |
return false; | |
} | |
function show_error (msg) { | |
var $error = document.querySelector('span'); | |
$error.textContent = msg; | |
} | |
function hide_error () { | |
document.querySelector('span').textContent = ''; | |
} | |
function save (eggs) { | |
var $img; | |
while ($img = document.querySelector('img')) { | |
$img.parentNode.removeChild($img); | |
} | |
for (var i = 0; i < eggs; i++) { | |
var $egg = document.createElement('img'); | |
$egg.src = 'one-egg.png'; | |
document.body.appendChild($egg); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment