Last active
May 11, 2017 22:22
-
-
Save kristin-henry-sf/2447027fef2edc57ca0c74516a3f518f to your computer and use it in GitHub Desktop.
Buttons Controlling Color: Using form elements to control DOM, with D3
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> | |
<meta charset="utf-8"> | |
<style> | |
body { | |
font: 12px sans-serif; | |
background-color: teal; | |
} | |
.buttons-div | |
{ | |
margin: 0 auto; | |
width: 140px; | |
height: 140px; | |
position: absolute; | |
} | |
</style> | |
<body> | |
<h1>Buttons with Colors</h1> | |
<p>Using form elements to control DOM, with D3.</p> | |
<div class='container' > | |
<div class="buttons-div"> | |
<h2>Select Variables</h2> | |
</div> | |
<div id="chart1"></div> | |
</div> | |
<script src="//d3js.org/d3.v3.min.js"></script> | |
<script> | |
drawRadioButtons(); | |
function drawRadioButtons(){ | |
var targ = d3.select(".buttons-div"); | |
var grp1 = {'name': 'Colors', 'buttons': [ | |
{'value':'teal', 'label':'teal', 'checked':true}, | |
{'value':'#a02b42', 'label':'red', 'checked':false}, | |
{'value':'#3a4e87', 'label':'blue', 'checked':false}, | |
{'value':'#82af80', 'label':'green', 'checked':false} ]} | |
targ.append('div') | |
.append('p') | |
.text(function(){return grp1['name']; }); | |
for(button in grp1['buttons']){ | |
var b = grp1['buttons'][button]; | |
console.log(b['label']) | |
drawRadioButton(targ, grp1['name'], b['label'], b['value'], b['checked']) | |
} | |
} | |
//------------------------------------------------------------------------------------- | |
// event listeners and actions | |
var inputElems = d3.selectAll("input"); | |
inputElems.on("change", changeColor); | |
function changeColor(){ | |
d3.select('body') | |
.style('background-color', this.value) | |
} | |
//------------------------------------------------------------------------------------- | |
//ToDo: move font sizing to external css, and give this a group-class for styling!! | |
function drawRadioButton(targ_div, grp_name, label_txt, value, checked, fontsize){ | |
if(checked === undefined) { checked = false; } | |
if(fontsize===undefined){ fontsize = '10px'} | |
var button = targ_div.append('div') | |
button.append('label') | |
.text(function(d){ return label_txt; }) | |
.style('font-size', fontsize) | |
var radio = button.append('input') | |
.attr('type', 'radio') | |
.attr('name', grp_name) | |
.attr('value', value) | |
.style('float', 'left') | |
.style('vertical-align', 'bottom') | |
if(checked){ radio.attr('checked', 'checked') } | |
targ_div.append('br') | |
return button; | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment