Forum

Thread tagged as: Question

Open pdf asset in new window?

I have a bunch of assets that are pdf files and they are placed in a single text block as links amongst the text (I'm using the textile menu bar and can place them with either the image or file icon). It works well except the client wants the pdf to open in a new browser tab when the link is clicked. Is this possible? Cheers.

Alan Coggins

Alan Coggins 0 points

  • 3 years ago
Drew McLellan

Drew McLellan 2638 points
Perch Support

Yes, but your best bet is probably to use JavaScript to do it.

Here's something similar: https://css-tricks.com/snippets/jquery/open-external-links-in-new-window/

I'm new to Perch and certainly no expert, but my understanding is that "target='_blank'" is allowed in HTML5 (having been deprecated in XHTML), and that's the solution I've used for opening PDFs where (IMO) it doesn't make sense to open the new document in the current window/tab.

I've also discovered that performance varies with browser. Firefox is good at opening files without requiring you to save them. Chrome likes you to download and save them first. (For avoidance of doubt, Firefox is saving them too, but is making less fuss about it, and probably deletes a temporary file afterwards).

CSS-Tricks have some interesting comments here: https://css-tricks.com/use-target_blank/

Thanks Drew and Tim. I guess my question should really have been "how do I make it happen". I can easily do it on a straight html page, but the links are being put in place by Perch. Just to be clear, I have this on the web page:

<?php perch_content('Pressure'); ?>

and I'm using the default text_block.html template:

<perch:content id="text" type="textarea" label="Text" textile="true" editor="markitup" size="xxl" imagewidth="900" imageheight="600" />

How do I put any parameters, such as "target='_blank'", onto the links that are generated within this structure?

Drew McLellan

Drew McLellan 2638 points
Perch Support

It's not easy if you've got links embedded in a textarea, hence a quick bit of JavaScript being a simple solution.

Ah, so javascript on the php page will do this. OK, I'll have to put my javascript expert (a.k.a. my son) onto this one. Thanks.

If anyone else is interested this is the code we used to target the pdf files...

var links = document.getElementsByTagName("a");

for (i = 0; i < links.length; i++) {
  if (links[i].href.endsWith(".pdf")) {
    links[i].onclick = function () {
      window.open(this.href, '_blank');
      return false;
    }
  }
}

Thanks for the advice Drew.