Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set div width using D3

I created a div in my html,

<div id="search"></div>

I want to set its width to 15% of my window width in my Javascript. I'm attempting to use D3 to do this:

var width = 0.15 * window.innerWidth,
    height = 0.95 * window.innerHeight;

var searchcolumn = d3.select("#search")
                    .attr("width", width)
                    .attr("height", height);

I can see in the DOM, the width and height of my div has been changed: enter image description here

However, in the rendered html the div is just 10px x 10px.

enter image description here

Why does this happen? I do not have any CSS that overwrites the size of the div. How do I set my div to my desired width?

like image 259
Zening Qu Avatar asked Nov 20 '14 05:11

Zening Qu


2 Answers

This is an old post but for anyone else wanting to solve this, the following will work :

var width = 0.15 * window.innerWidth,
    height = 0.95 * window.innerHeight;

var searchcolumn = d3.select("#search")
                    .style("width", width + 'px')
                    .style("height", height + 'px');

I have added is + 'px'; and also changed .attr to .style as it's the CSS you are working with here.

Working code :

var data = [10,12,6,8,15];

var svg = d3.select('body')
//.append('svg')
.attr('width', 500).attr('height', 500);

var width = 0.15 * window.innerWidth,
    height = 0.95 * window.innerHeight;
     
svg.selectAll('div')
  .data(data)
  .enter().append('div')
  .attr('class','divs')
  .attr('x', function(d,i) { d.clicked=false; return 100+100*i; })
  .attr('y', function(d,i) { return 0; })
  .style('width', width + 'px')
  .style('height',height +'px')
  .attr('background-color', function() { return 'red'; }) 

  .text(function(d){ return d;})
.divs { 
  background: blue;  
  display:inline-block;
  float:left;
  margin:5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
like image 64
thatOneGuy Avatar answered Oct 16 '22 08:10

thatOneGuy


Try:
d3.select("#search") .style("height", height) .style("width", width);

like image 28
Trojanware Avatar answered Oct 16 '22 08:10

Trojanware