Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make any link with .pdf open in new window with jQuery?

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.

like image 216
Digi Jeff Avatar asked Jan 03 '13 14:01

Digi Jeff


3 Answers

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');
});
like image 90
Rory McCrossan Avatar answered Sep 27 '22 19:09

Rory McCrossan


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;
        }
    });
like image 34
David Thomas Avatar answered Sep 27 '22 18:09

David Thomas


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

like image 27
gabssnake Avatar answered Sep 27 '22 20:09

gabssnake