Search code examples
javascriptamchartsamcharts4

JS Amcharts - Responsive relocate position of legend


JS Amcharts - Responsive relocate position of legend

How to change the position of the legend responsivly from "right" to "bottom" when let say the screen is (gets resized) smaller than 992px?

html:

<div id="chartdiv"></div>

js:

var chart = am4core.create("chartdiv", am4charts.PieChart);

chart.data = [{
  "country": "Lithuania",
  "litres": 501.9
}, {
  "country": "Czech Republic",
  "litres": 301.9
}, {
  "country": "The Netherlands",
  "litres": 50,
  "hidden": true
}];

var pieSeries = chart.series.push(new am4charts.PieSeries());
pieSeries.dataFields.value = "litres";
pieSeries.dataFields.category = "country";
pieSeries.dataFields.hidden = "hidden";

chart.legend = new am4charts.Legend();
chart.legend.fontSize = 12;
chart.legend.position = "right";
chart.legend.markers.template.width = 12;
chart.legend.markers.template.height = 12;

Fiddle: https://codepen.io/anon/pen/wLEomN


Solution

  • You can just watch the window resize event and change the chart.legend.position according to the window width:

    window.addEventListener('resize', () => {
      if (window.innerWidth < 992) {
        chart.legend.position = "bottom";
      } else {
        chart.legend.position = "right";
      }
    }, true);
    

    Here I forked your code pen and added my solution.