How to add anchor links in Datawrapper visualizations

In this article, you'll learn how to let your readers open links in the same page – i.e. how to create anchor links to jump to specific parts of the same page where your visualization is embedded. 

Why do links open in new tabs? 

In Datawrapper, when you click on a link inserted using an a tag it will always open in a new tab. This is because Datawrapper automatically adds an attribute target="_blank" to any <a> tag. This instructs the browser to open the link in a new tab, and is required for security reasons.

But what if you want to the link to open on the same page or create anchor-links to jump to specific part of the page? One workaround is to use our chart interaction event listening library, more specifically the hash.change event

See an example in action here

See the Pen Anchor Links Demo by Aya (@aya_dw) on CodePen.

How to configure anchor-links on your visualization and your web page

Here's an example of a web page where we have a map and a table that shows the locations of several attractions in Berlin. We want to link each location to the description text further down on the same page: 

There are two parts to implementation–in your visualization and on your web page: 

1
Add hash-links to <a> tag

An anchor link is a link that leads to another part of the same page that has a specific id. This can be represented by a hash-link which consists of # symbol followed by a unique id (e.g. #reichstag#brandenburg-gate).

 The <a> tag should also include the target="_self" attribute (the rel attribute will get added automatically): 

<a href="#brandenburg-gate" target="_self" rel="nofollow noopener noreferrer">Brandenburg 
Gate</a>
	
2

Add id attributes to the HTML of your web page 

Once you've assigned hash-links, you can now add an id attribute to each part of the website where you want to direct your readers to (e.g. id="reichstag"id="brandenburg-gate"). 

3
Add a helper function to listen to events
The next step is to enable event listening on your web page. To do so, include the following script tag in the <header> section of your web page: 

 <script src="//static.dwcdn.net/js/events.js"></script>
	
4

Include a script like below to listen out for the hash.change event. 👉  Read our developer docs to learn more about listening to chart interaction events

datawrapper.on('hash.change',(event) => {
  var chart = document.getElementById("datawrapper-chart-"+event.chartId);
  if (event.data.hash === '#none') return;
  console.log(`hash has changed to ${event.data.hash}`);


  // do something
  window.location.hash = event.data.hash;
  // reset hash
  chart.src = chart.src.replace(event.data.hash,'#none');
});
	

That's it! You can hover over the visualizations below and click on 'Edit this chart' button to create a copy in your account: 

Reach out to support@datawrapper.de if you have any questions.