Skip to content

Instantly share code, notes, and snippets.

@johntron
Last active August 29, 2015 14:16
Show Gist options
  • Save johntron/60286857300172667926 to your computer and use it in GitHub Desktop.
Save johntron/60286857300172667926 to your computer and use it in GitHub Desktop.

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.

How many eggs would you like: <input> <span></span><br />
<script src="main.js"></script>
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