JSFiddle - React, Tailwind, and code Playground
by niki4810
HTML
<script src="https://rawgithub.com/mbostock/d3/master/d3.js"></script>
<input type="text" class="txtDiscount"></input>
<br/>
<div class="graph"></div>
CSS
svg {
padding:10px 20px 10px 10px;
}
JavaScript
$(function () {
$(".txtDiscount").keyup(function(e){
var val = +$(".txtDiscount").val();
plotGraph(val);
});
});
var plotGraph = function (val) {
$(".graph").empty();
var dataset = [val];
//Width and height
var w = 100;
var h = 30;
var min = 5;
var max = 10;
//Create SVG element
var svg = d3.select(".graph")
.append("svg")
.attr("width", w)
.attr("height", h);
//horizontal axis
svg.append("line")
.attr("x1", 0)
.attr("y1", 10)
.attr("x2", 100)
.attr("y2", 10)
.style("stroke", "black");
//left vertical axis
svg.append("line")
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", 0)
.attr("y2", 20)
.style("stroke", "black");
//right vertical axis
svg.append("line")
.attr("x1", 100)
.attr("y1", 0)
.attr("x2", 100)
.attr("y2", 20)
.style("stroke", "black");
//data indicator rectangle
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", 10)
.attr("height", 25).attr("x", function (d, i) {
return d; //Bar width of 20 plus 1 for padding
}).attr("fill", function (d) {
if (d <= min) {
return "green";
} else if (d > min && d <= max) {
return "orange";
} else {
return "red";
}
});
//text indicator
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function (d) {
return d;
})
.attr("x", function (d, i) {
return d;
}).attr("y", function (d, i) {
return "-1";
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "black");
};