Intro to JS - Prime Numbers Example
HTML
<section>
<!-- We bind to the element's ID using JavaScript -->
<button id="myButton">Next Prime Number</button>
<div id="message-output">2</div>
</section>
<div id="prime-blocks"></div>
CSS
section {
position: absolute;
width: 200px;
height: 200px;
border-radius: 5px;
background: rgba(0,20,0,.1);
text-align:center;
padding: 15px;
z-index: 1;
}
section button {
background: black;
color: white;
font-size: 18px;
outline: none;
}
#message-output {
display: relative;
margin: 0 auto;
font-family: arial;
font-size: 20px;
line-height: 100px;
color: gray;
text-align: center;
background: lightgreen;
width: 100px;
height: 100px;
border-radius: 50%;
margin-top: 15%;
}
#prime-blocks {
position: absolute;
top: 0;
left: 0;
z-index: 0;
width: 150%;
overflow: hidden;
}
#prime-blocks div {
float: left;
}
JavaScript
//this is a single line comment
/*
this is a multi-line comment
"the craft of programming is the factoring of a set of requirements into a set of functions and data structures."
Crockford, Douglas (2008-05-08). JavaScript: The Good Parts
*/
//this is a variable to hold prime numbers
//we start with the first prime number, 2
var primeNumber = 2;
/*
What is prime?
A prime number is an integer greater than one whose positive divisors (factors) are one and itself. i.e. 2,3,5,7,11,...
*/
//this a function definition
var getNextPrimeNumber = function() {
/*
variable values can be passed to other variables
variables inside a function block within that function's scope
variables defined outside the function can still be accessed
*/
//other functions can be defined within functions
var calculatePrime = function() {
//increment the prime number by 1
primeNumber = primeNumber + 1;
//store the value from primeNumber as the dividend
var dividend = primeNumber;
//use one less than the value stored within the dividend for divisor
var divisor = dividend - 1;
//the modulo "%" operator returns the remainder of a division
while(dividend % divisor !== 0) { //loops while condition is met
divisor--; //subtract 1 from divisor and try again
//note* another way to decrement a value by one is to write "val--"
}
if(divisor !== 1) {
/*
If the number is not equal to 1, then we call this function again,
which increments the primeNumber variable by 1, and tests to see
if it is prime. This is called "recursion"
*/
//alert('doing recursion');
calculatePrime();
}
}
calculatePrime();
return primeNumber;
}
var myButton =...