JSFiddle - React, Tailwind, and code Playground
HTML
<div class="game">
<h3>Who is this?</h3>
<div id="namesOutput"></div>
</div>
CSS
.btn {
border: 1px solid #fff;
display: block;
font-size: 18px;
margin-bottom: 12px;
padding-bottom: 14px;
padding-top: 14px;
width: 100%;
}
.btn:hover {
background-color: #fff;
color: blue;
text-decoration: none;
transition: all .3s;
}
.btn--correct,
.btn--correct:hover {
background-color: green;
border-color: green;
color: white;
}
.btn--incorrect,
.btn--incorrect:hover {
background-color: red;
border-color: red;
color: white;
}
JavaScript
// courtesy of http://stackoverflow.com/a/6274381/648350
function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
// courtesy of http://stackoverflow.com/a/6700/648350
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
$(document).ready(function() {
var answers = 3;
//
// Retrieve JSON
//
$.getJSON("https://gist.githubusercontent.com/keenanpayne/ada118875c2a5c672cd3/raw/8a72fc99c71c911f497200a7db3cc07b2d98dc82/sample.json", function(result) {
var numberOfResults = Object.size(result);
var staffNumber = 0;
var correctAnswer = "";
var correctAnswerID = Math.floor((Math.random() * numberOfResults) + 1);
var outputHtml = [];
// Loop through set
$.each(result, function(i, field) {
staffNumber++;
if (staffNumber == correctAnswerID) {
correctAnswer = '<a class="btn gameBtn" title="' + staffNumber + '">' + field.name + '</a>'; // store our correct answer
}else{
outputHtml.push('<a class="btn gameBtn" title="' + staffNumber + '">' + field.name + '</a>'); // add all the other answers
}
});
outputHtml = shuffle(outputHtml).slice(0, answers - 1); // -1 because one answer will come from the 'correct' answer
outputHtml.push(correctAnswer); // add correct answer after slicing
outputHtml = shuffle(outputHtml); // shuffle the correct answer around again
outputHtml = outputHtml.join(''); // flatten outputHtml into single string
$("#namesOutput").append(outputHtml); // add it to the DOM
//
// Check answer
//
$(".gameBtn").click(function(e) {
e.preventDefault();
if ($(this).attr('title') == correctAnswerID) {
$(this).addClass("btn--correct");
$('.btn').not(".btn--correct").addClass("btn--incorrect");
} else {
...