Search code examples
rshinylearnr

in learnr, how to make external links open in new tab


I am using the r package learnr and would like all links (to external material) to open in a new tab. I could probably just add

<base target="_blank"> 

but I don't know how to add header tags in learnr. I believe this isn't possible in ordinary markdown. I know I can just type the html for each external link but that is a real drag.


Solution

  • Yihui Xie has a helpful post containing a JavaScript snippet to do just this: https://yihui.org/en/2018/09/target-blank/

    In the context of a learnr tutorial, you could add Yihui's function using the following js code chunk added to the top of your .Rmd source (above your first level 2 (##) heading).

    
    ```{js target-blank, echo=FALSE}
    $(document).ready(function() {
      var links = document.getElementsByTagName('a');
      for (var i = 0; i < links.length; i++) {
        if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) {
          links[i].target = '_blank';
        }
      }
    });
    ```