I'm completely new to css and javascript and need some help building a bar chart. My problem, among others, are that I need to auto adjust the width of my bar DIV inside my box DIV. So if there is 2 values in the "element"-list, then they should stretch and fill the DIV, but if there is 10 they need to shrink.
Javascript
var element = [ 189, 128, 28, 88];
var _body = document.getElementsByTagName("body")[0];
var _div = document.createElement("div");
_div.id = "box";
_body.appendChild(_div);
var mainbox = document.getElementById("box");
for (var i=0; i <= element.length; i++){
var bars = document.createElement("div");
bars.setAttribute("class", "bar");
bars.id = "bar";
bars.style.height = element[i]+"px";
mainbox.appendChild(bars);
}
var text = document.createElement("div");
text.setAttribute("class", "text");
text.innerHTML="Mitt stapeldiagram";
mainbox.appendChild(text);
CSS I've set the "width"-value to 100%, but I don't know if that's right?
.text{
font-family:"Times New Roman", Times, Sans-serif;
font-size:28px;
font-weight:bold;
color:gray;
text-align:center;
margin-top:370px;
overflow:hidden;
}
#box{
overflow:hidden;
width: 500px;
height: 400px;
margin-top:50px;
margin-left:50px;
padding:10px;
background-color:lightgray;
border-top:3px solid black;
border-right:3px solid black;
box-shadow: 10px 10px 5px #888;
}
.bar{
float:left;
position:relative;
width:100%;
margin:3px;
background-color:blue;
box-shadow: 5px 2px 5px #888;
}
Try this
var element = [189, 128, 28, 88];
var _body = document.getElementsByTagName("body")[0];
var _div = document.createElement("div");
_div.id = "box";
_body.appendChild(_div);
var mainbox = document.getElementById("box");
// set total box height
var mainboxHeight = 400;
// get total
var total = 0;
for (var i = 0; i < element.length; i++)
total += parseInt(element[i]);
for (var i = 0; i <= element.length; i++) {
// change elements to percentage
var elementPerc = Math.round((element[i] / total) * 100);
var bars = document.createElement("div");
bars.setAttribute("class", "bar");
bars.id = "bar";
var heightPerc = Math.round((elementPerc / 100) * mainboxHeight);
bars.style.height = heightPerc + "px";
mainbox.appendChild(bars);
}
var text = document.createElement("div");
text.setAttribute("class", "text");
text.innerHTML = "Mitt stapeldiagram";
mainbox.appendChild(text);
See these live demos
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.