Created
March 15, 2017 06:45
-
-
Save phpfiddle/780c6bc58fe613792b3e70a56bcd0ddd to your computer and use it in GitHub Desktop.
[ Posted by Joe Bloggs ] Display CSS colour names and hex code values in appropriately coloured boxes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>Colours</title> | |
<meta name=viewport content="width=device-width, initial-scale=1"> | |
<style> | |
.colour-div { | |
display: inline-block; | |
padding: 10px; | |
border: 1px solid #666; | |
width: 220px; | |
font-size: 90%; | |
} | |
</style> | |
</head> | |
<body> | |
<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> | |
<script> | |
// 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) { | |
callback(xhttp); | |
} | |
}; | |
// Use HTTP GET method to retrieve data | |
xhttp.open('GET', url, true); | |
xhttp.send(); | |
} | |
function run() { | |
getData('get-colours.php', loadColours); | |
} | |
run(); | |
// 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); | |
//console.log(names); | |
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"; | |
displayBox.appendChild(divEl); | |
} | |
} | |
</script> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment