numbers-game
by Carin Camen
HTML
<div class="controls">
<button data-num="1">
1
</button>
<button data-num="2">
2
</button>
<button data-num="3">
3
</button>
<button data-num="4">
4
</button>
<button data-num="5">
5
</button>
<button data-num="6">
6
</button>
<button data-num="7">
7
</button>
<button data-num="8">
8
</button>
<button data-num="9">
9
</button>
<button data-num="10">
10
</button>
</div>
<div class="numbers">
<!--Javascript will put numblocks in this area -->
</div>
<h2>
Tip Box
</h2>
<div class="tip">
</div>
</div>
CSS
.controls {
margin: 30px 0 30px 0;
}
.number {
width: 30px;
height: 30px;
border: solid 2px black;
text-align: center;
vertical-align: middle;
font-family: 'Oswald', sans-serif;
font-size: 18px;
color: white;
background-color: blue;
display: inline-block;
margin: 0 10px 10px 0;
}
.highlight {
background-color: purple;
opacity: .4;
border: solid 2px purple;
}
.tip {
margin: 10px 0 0 10px;
width: 620px;
height: 100px;
border: solid 1px black;
background-color: purple;
color: white;
font-size: 2em;
padding: 10px;
}
JavaScript
/**
* Generates number blocks and appends them to a specified element
* on the DOM.
*
* @param element - Requested DOM element to be appended
* @param count - Number of blocks to be appended (defaults to 100)
*/
var _generateNumbers = function(element, count=100) {
for(var i = 1; i <= count; i++) {
// If they didn't provide an element, default one
if(!element) {
element = $('.numbers');
}
// generate our HTML and add it to the requested element
// providing it a data number to be processed later
element.append(
'<div class="number" data-num="' + i + '">' + i + '</div>'
);
}
}
/**
* Adds or removes a highlight from a block, depending on if it
* matches the filter criteria.
*
* @param element - Block to be highlighted or unhighlighted
* @param filterNum - The number to filter off of.
*/
var _highlightNumber = function(element, filterNum) {
var num = $(element).data().num;
// If the block's number is perfectly divisible by the filter
// then add a highlight, otherwise remove any existing highlight
if(num % filterNum === 0) {
$(element).addClass('highlight');
} else {
$(element).removeClass('highlight');
}
}
/**
* Handles the click event for the filter buttons.
*
* @param event
*/
var _btnClickHandler = function(event) {
// Determine what button was clicked on by looking at the 'target'
var btn = event.target;
// Get it's specified filter number off of the data attribute
var filterNum = $(btn).data().num;
// Iterate over all number blocks and determine if they should
// be highlighted or not
$('.number').each(function(index, element) {
_highlightNumber(element, filterNum);
});
/**
* Show Tip Box tips based upon Avatar selected
*/
if (1 === filterNum) {
$('.tip').text('One dialogue here.');
} else if (2 === filterNum) {
$('.tip').text('Two dialogue here.');
} else if (3 === filterNum) {
$('.tip').text('Three dialogue here.');
}...