FizzBuzz - jQuery

by Thomas Orthbandt

HTML

<div id="container">
  <form id="fizzbuzz">
    <h2>Fizzbuzz</h2>
		<p>
		Write a program that has a starting and finishing number.</p>
		<ul>
			<li>Any multiples of three (3) print “Fizz” instead of the number.</li>
			<li>Any multiples of five (5) print “Buzz”.</li>
			<li>For numbers which are multiples of both three (3) and five (5) print "FizzBuzz”.</li>
		</ul>
    <input type="text" name="start" id="start" placeholder="Starting Number">
    <input type="text" name="finish" id="finish" placeholder="Finishing Number">
    <br>
    <input type="submit" value="GO!" id="submit">
  </form>

  <div id="output"></div>
  <div id="error"></div>
</div>

CSS

#container {
  width: 90%;
  margin: 0 auto;
}
p,ul {
	text-align: left;
}

span {
  border: 1px solid #999;
  border-radius: 3px;
  width: 80px;
  height: 20px;
  padding: 5px;
  margin: 5px;
  float: left;
  text-align: center;
  background-color: green;
  display: none;
}

.fizz {
  background-color: pink;
}

.buzz {
  background-color: lightblue;
}

.fizzbuzz {
  background-color: purple;
}

#submit {
  width: 110px;
  height: 50px;
  border-radius: 10px;
  background-color: #666;
  color: #fff;
  border: none;
  margin: 10px;
  clear: both;
}

#submit:hover {
  background-color: #888;
}

form {
  text-align: center;
}

input {
  padding: 5px;
  border-radius: 5px;
  border: 1px solid #CCC;
  height: 30px;
  margin: 5px;
}

.error {
  color: red;
}

JavaScript

$(function() {
  $("#fizzbuzz").submit(function(event) {
    // Create a start variable and parse the numbers value
    // Create a finish variable and parse the numbers value
    var start = parseInt($("#start").val());
    var finish = parseInt($("#finish").val());

    // check that the input values are numbers
    if (!isNaN(start) && !isNaN(finish)) {
      // loop through numbers
      var i;
      for (i = start; i <= finish; i++) {
        if (i % 3 === 0 && i % 5 === 0) {
          $("#output").append("<span class='fizzbuzz'>FizzBuzz</span>");
        } else if (i % 3 === 0) {
          $("#output").append("<span class='fizz'>Fizz</span>");
        } else if (i % 5 === 0) {
          $("#output").append("<span class='buzz'>Buzz</span>");
        } else {
          $("#output").append("<span>" + i + "</span>");
        }
      }
      $("#output span").fadeIn(400);
    } else {
      // if the inputs are not valid numbers
      $("#error").append("<p class='error'>Please enter a valid number in both boxes</p>");
    }
    // prevent form submission
    return false;
  });

  // empty the output & error divs
  $('input').on('focus', function() {
    $("#output span").fadeOut(400, function() {
      $("#output").empty();
    });
    $("#error").empty();
  });
}); // end ready