Reputation: 209
First, this: Resize svg when window is resized in d3.js is not what I'm looking for.
My graph width is defined as the following few functions:
var element = document.getElementById('front'),
style = window.getComputedStyle(element),
divWidth = parseInt(style.getPropertyValue('width'), 10),
divHeight = parseInt(style.getPropertyValue('height'), 10);
window.onresize = function() {
divWidth = parseInt(style.getPropertyValue('width'), 10),
divHeight = parseInt(style.getPropertyValue('height'), 10);
};
var margin = {top: 20, right: 40, bottom: 90, left: 40},
width = divWidth - margin.left - margin.right,
height = divHeight - margin.top - margin.bottom;
Which works perfectly when the page is generated. As you can see, the variable is dynamically updated as the screen gets shifted. What I want to know is how to update the width of the chart at the same time as the variable gets reassigned.
Link and source for the project: Cards
An additional question after reading up some more: What is the best way to do the alternative to window.resize
with a div in place of the window.
EDIT: Found a great div resize tool: http://www.backalleycoder.com/2013/03/18/cross-browser-event-based-element-resize-detection/
Upvotes: 0
Views: 309
Reputation: 1623
Using the polling technique, you can solve the issue in this way:
addResizeListener(target, function()
{
var style = window.getComputedStyle(target);
divWidth = parseInt(style.getPropertyValue('width'), 10);
divHeight = parseInt(style.getPropertyValue('height'), 10);
width = divWidth - margin.left - margin.right;
height = divHeight - margin.top - margin.bottom;
document.getElementById('front').innerHTML = '<span style="font-size: 40px; font-family:icons; cursor:pointer" id="flip" onclick="flipper(\'flipper\')"></span>';
makeTestGraph();
makeSliderGraph();
});
Upvotes: 1
Reputation: 89
I believe that what you're trying to do can be solved with the preserveAspectRatio attribute and a wrapper div. Here is a blog post on the subject
When initializing your svg element, simply set the viewBox and perserveAspectRatio attributes. The element will then become responsive in relation to its immediate parent.
<svg id="chart" width="600" height="200"
viewBox="<LEFT> <TOP> <WIDTH> <HEIGHT>"
perserveAspectRatio="xMinYMid[none/etc]">
Depending on your need, you may want to use a different scaling rule.
A JSFiddle credit to Shawn Allen, the author of this snippet.
Upvotes: 0