Custom Datawrapper script embed setup

by elanadw

HTML

<!-- this script registers the global datawrapper object, and datawrapper.render function on the window -->
<script src="https://datawrapper.dwcdn.net/lib/datawrapper.js"></script>


<h2>Article title</h2>
<article>
  <p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean nec quam quis ante vulputate volutpat. Proin auctor tristique ligula non tempus.
  </p>
  <!-- custom embed markup - needs a class for generic selection, and a way to identify the chart id -->
  <div class="datawrapper-embed" data-chart-id="3MOum"></div>
  <p>
  Morbi id mattis turpis. Aliquam vestibulum justo eu ultricies luctus. Ut varius at mauris vel fermentum. Phasellus bibendum efficitur magna at feugiat. Praesent libero libero, blandit nec erat non, malesuada efficitur nibh.
  </p>
  <div class="datawrapper-embed" data-chart-id="XskMo"></div>
</article>

CSS

body {
  max-width: 600px;
  margin: auto;
  font-family: sans-serif;
}

JavaScript

// collect all embeds on the page
const embeds = Array.from(document.querySelectorAll('.datawrapper-embed'));

embeds.forEach(embed => {

  // create URL for visualization's embed.json
  const chartId = embed.dataset.chartId;
  const chartDataUrl = `https://datawrapper.dwcdn.net/${chartId}/embed.json`;

  // create target element inside of embed wrapper
  const target = document.createElement('div');
  embed.appendChild(target);

  // load render data from chart's embed.json
  fetch(chartDataUrl)
    .then((res) => res.json())
    .then((embedData) => {
    // then pass it to datawrapper.render call, along with { target, flags }
    datawrapper.render(embedData, {
      // the node that will be turned into the web component
      target,
      // optionally include flags (e.g dark, fitchart) here
      // see https://developer.datawrapper.de/docs/render-flags
      flags: {},
    });
  });
});