Last active
October 10, 2015 14:50
-
-
Save gitfvb/2da58996d8fed975ecda to your computer and use it in GitHub Desktop.
Resize the fixed width of html elements to allow responsive design for e.g. d3 visualisations
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
/* | |
description: | |
This function allows you to resize an html element | |
when the screen size is changing (resize the browser or ). | |
This allows you responsive design on some elements with | |
fixed pixel sizes. This can be used e.g. for d3.js visualisations. | |
author: Florian von Bracht | |
email: [email protected] | |
parameters: | |
objID: The id of the html element. | |
margin: optional. You can define a margin around the element like {top: 20, right: 20, bottom: 20, left: 40}. | |
usage: | |
If you have an element like this | |
<div id="d3-line"></div> | |
you can resize it like in the following code. When the whole document was loaded, the element size | |
will be set and then everytime when the resolution changes. | |
// load() event and resize() event are combined | |
$(window) | |
.ready(function() { | |
responsiveWidth('d3-line', {top: 20, right: 20, bottom: 20, left: 40}); | |
}) | |
.resize(function() { | |
responsiveWidth('d3-line', {top: 20, right: 20, bottom: 20, left: 40}); | |
}); | |
requirements: | |
- This function uses an associative javascript array function | |
for the margin array. This can be found also in my gists. | |
- You will also need jQuery for this. | |
*/ | |
function responsiveWidth(objID, margin) { | |
// set the responsive width of the screen | |
factor = 0.35; // this example means 35% of 100% screen | |
// get the browser dimensions | |
width = $( window ).width(); | |
height = $( window ).height(); | |
// use a margin, if needed | |
if (margin != undefined) { | |
if ($.assocArraySize(margin) != 4) { | |
var margin = {top: 0, right: 0, bottom: 0, left: 0}; | |
} | |
} else { | |
var margin = {top: 0, right: 0, bottom: 0, left: 0}; | |
} | |
// calculate the new width in pixels | |
newWidth = Math.floor(width*factor)+margin['left']+margin['right']; | |
// set the width of the given element by the html id | |
document.getElementById(objID).setAttribute('width',newWidth); | |
// return the width in addition to the change before so we can use the function also to initiate the width | |
return newWidth; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment