Make a .pdf link in a new window using jQuery?

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

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

In that:

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

All files are in the /pdf folder, if that helps.

+6
source share
4 answers

To do this, you can select any element a that has the href property ending in .pdf and add the target="_blank" attribute to it. Try the following:

 $(function() { $('a[href$=".pdf"]').prop('target', '_blank'); }); 
+20
source

In one case, if you want links that do not end in pdf to open on one page:

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

jQuery one-liner:

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

Also in vanilla Javascript:

 [].filter.call(document.querySelectorAll('a'), function(a){ return a.href.match('\\.pdf$') ? a.target = '_blank' : 0; }); 

Or maybe:

 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

0
source

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

Now write ActionResult as 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"); } } 
0
source

All Articles