Get google chart image to fill div width

I retrieve some line charts using the Google chart API and put them in a DIV as follows:

<div class="chart" style="display:block"> <img src="http://chart.apis.google.com/chart?chs=620x40&cht=lfi&chco=0077CC&&chm=B,E6F2FA,0,0,0&chls=1,0,0&chd=t:27,25,25,25,25,27,100,31,25,36,25,25,39,25,31,25,25,25,26,26,25,25,28,25,25,100,28,27,31,25,27,27,29,25,27,26,26,25,26,26,35,33,34,25,26,25,36,25,26,37,33,33,37,37,39,25,25,25,25"> </div> 

I need to pass the height and width of the required graphic, and the Google Chart API will display it, for example. chs=620x40 . I would like the graphic image to be with my parent div . I need to calculate the width and dynamically build this chart url to get a chart image of the right size. How can i do this?

(I'm not too bright with jQuery, and I try to avoid using some bloated libraries)

thanks

+2
source share
1 answer

You can use the following JavaScript (with jQuery):

 function sizeCharts(){ $(".chart").each(function(){ var w = $(this).width(); var h = $(this).height(); // or just change this to var h = 40 $("<img>").attr("src","http://chart.apis.google.com/chart?chs=" + \ escape(w) + "x" + escape(h) + "&[etc]").appendTo(this); }); } $(function(){ sizeCharts(); var shouldResize = true; $(window).bind("resize",function(){ if(!shouldResize){ return; } shouldResize = false; setTimeout(function(){ sizeCharts(); shouldResize = true; },1000); }); }); 

Replace [etc.] with the rest of the URL you want to use. What happens in the code above, it will iterate over everything using the chart class on your page and put the chart in it with the appropriate size.

If you are using a liquid layout (i.e. your site is resizing to fill a certain percentage of the screen), then you will also want to include the $(function(){ ... }) bit, which will work with the same code when the page will be changed. Pay attention to the use of timers here, otherwise the same graph will be reloaded for each pixel that will resize the window.

+1
source

Source: https://habr.com/ru/post/1205936/


All Articles