Create a gist now

Instantly share code, notes, and snippets.

[ Posted by Joe Bloggs ] Display CSS colour names and hex code values in appropriately coloured boxes
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta name=viewport content="width=device-width, initial-scale=1">
.colour-div {
display: inline-block;
padding: 10px;
border: 1px solid #666;
width: 220px;
font-size: 90%;
<div id="container">
<h1>Colour names and their hex equivalents</h1>
<!-- Empty div that will be filled with divs displaying colours -->
<div id="display-box"></div>
// Get a handle to the display div
let displayBox = document.getElementById('display-box');
// This function makes a connection to the php script
// and the callback function is run when the connection
// return data
function getData(url, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Use HTTP GET method to retrieve data'GET', url, true);
function run() {
getData('get-colours.php', loadColours);
// Turn the returned data, which is this form: "{"aliceblue":"#f0f8ff", "antiquewhite": "#faebd7",...}"
// into a JavaScript object literal that is in this form: {"aliceblue":"#f0f8ff", "antiquewhite": "#faebd7",...}
function loadColours(xhttp) {
let colours = JSON.parse(xhttp.responseText);
for (key in colours) {
let divEl = document.createElement('div');
divEl.setAttribute('class', 'colour-div');
divEl.setAttribute('style', 'background-color:' + key);
divEl.textContent = key + ", " + colours[key] + "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment