6

How can I have all links with a .pdf file extension open in a new window using jQuery? I need to change this:

<a href="domain.com/pdf/parkingmap.pdf">parking map</a> 

In to this:

<a href="domain.com/pdf/parkingmap.pdf" target="_blank">parking map</a> 

All files are in a /pdf folder if that helps.

4 Answers 4

21

To achieve this you can select any a element which has a href property ending with .pdf, and add a target="_blank" attribute to it. Try this:

$(function() { $('a[href$=".pdf"]').prop('target', '_blank'); }); 
Sign up to request clarification or add additional context in comments.

5 Comments

Is there a reason you are using .prop('target', '_blank'); instead of .attr('target', '_blank'); ?
@sircapsalot prop is used in cases where you are amending a property which is available through the POJS element object. Things like id, or src for example. api.jquery.com/prop
@RoryMcCrossan do I just need to add <script> $('a[href$=".pdf"]').each(function() { $(this).prop('target', '_blank'); }); </script> in the header? Doesn't seem to be working and nothing was added to links when I copied and pasted your code.
You also need a document ready handler. I'll update my answer to give you the whole thing.
@RoryMcCrossan I added " $(document).ready(function() {" and it seemed to work, thanks!
3

One way, assuming you want links not ending in pdf to open in the same page:

$('a').click( function(e){ e.preventDefault(); if (this.href.split('.').pop() === 'pdf') { window.open(this.href); } else { window.location = this.href; } }); 

Comments

2

jQuery one-liner:

$('a[href$=".pdf"]').attr('target','_blank'); 

Current Javascript:

for (let a of document.querySelectorAll("a")) { if (a.href.match("\\.pdf$")) { a.target = "_blank"; } } 

Older browsers :

var anchors = document.body.getElementsByTagName('a'); for (var i = 0; i < anchors.length; i++) { if(anchors[i].getAttribute('href').match('\\.pdf$') { anchors[i].setAttribute('target', '_blank'); } } 

Try it here : http://codepen.io/gabssnake/pen/KyJxp

Comments

1

<a onclick=ViewPdf(test.pdf) href=""> function ViewPdf(FileName) { var url = '../Home/GetPDF?fileName=' + FileName; window.open(url, '_blank'); }

Now write ActionResult like below

public ActionResult GetPDF(string fileName) { try { byte[] fileData = System.IO.File.ReadAllBytes(Functions.GetConfigValue("CDXFilePath") + fileName); string resultFileName = String.Format("{0}.pdf", fileName); Response.AppendHeader("Content-Disposition", "inline; filename=" + resultFileName); return File(fileData, "application/pdf"); } catch { return File(Server.MapPath("/Content/") + "FileNotFound.html", "text/html"); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.