1

I went to Pinboard's Resource page, got my widget and it all works beautifully. I've styled it up (sidebar on anwarchoukah.com) and am generally happy.

The code generated is

<script language="javascript" 
  src="http://pinboard.in//widgets/v1/linkroll/?user=Garbad&count=5">
</script>

My problem is that I want to have the links open in a new window - any ideas?

P.S. I'm not very good with JavaScript

achoukah
  • 1,345
  • 2
  • 10
  • 10

1 Answers1

1

[edit] The second answer is not going to work because async. loaded scripts are not allowed to write into the document! But the first one is shorter as well, it will only fail when the request to pinboard.in is slower than 500ms.

Working answer

So you would go the timeout route and run the script when some time has passed to make sure the pinboard script has run and its response is accessible by getElementsByTagName. your <scripttag would remain as is, you will only have to add the following javascript code in your main .js file:

window.onload = function() {
  setTimeout( function() {
    var anchors = document.getElementById( 'pinboard_linkroll' ).getElementsByTagName( 'a' );
    for ( var i = 0; i < anchors.length; i++ ) {
      anchors[i].setAttribute( 'target', '_blank' );
    }
  }, 500 );
};

Not working answer left for reference

first you have to hijack the loading of the script. then you can modify the attr target in the callback function.

this javascript goes into wherever your main scripts are loaded:

function loadScript( url, callback ) {

  var script = document.createElement( 'script' )
  script.type = 'text/javascript';

  if ( script.readyState ) {  // IE
    script.onreadystatechange = function() {
      if ( script.readyState === 'loaded' || script.readyState === 'complete' ) {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {  // Others
    script.onload = function() {
      callback();
    };
  }

  script.src = url;

  document.getElementById( 'pinboard_hook' )[0].appendChild( script );

}

window.onload = function() {

  loadScript( 'http://pinboard.in//widgets/v1/linkroll/?user=Garbad&count=5', function() {

    var anchors = document.getElementById( 'pinboard_linkroll' ).getElementsByTagName( 'a' );
    for ( var i = 0; i < anchors.length; i++ ) {
      anchors[i].setAttribute( 'target', '_blank' );
    }

  });

}

in your html you would replace the <script> tag with a simple wrapper like:

<span id="pinboard_hook"></span>
Community
  • 1
  • 1
Hans Spieß
  • 897
  • 7
  • 13
  • Thank you! With the first one, I get some warnings in the console, notably about the 500ms timeout.. Would it be advisable to extend the timeout or not, do you reckon? – achoukah Oct 12 '16 at 15:05