Andy Andy - 4 months ago 27
jQuery Question

Make any links in a Bootstrap modal open in a new window

I have a page which loads content into a Bootstrap (3.3.7) modal window. The content in the majority of these modals features 1 or more links.

I want any link that the user clicks on, in these modals, to open up in a new browser tab.

I can get this working by putting a

on each anchor, e.g.

<a href="" target="_blank">Link</a>

But this seems tedious as every time I output a link I have to add this tag.

Is there a way to just tell the browser to open any links found in a modal in a new window/tab?

I've searched around but most of the answers refer to loading the link inside the modal, which is not what I want to do here.

I also want the modal to remain un-touched, i.e. keep it open (don't close it), in the previous tab.


You can add the target attribute via jQuery targeting the elements:

$('#modal-name a').attr('target', '_blank');

Or you can bind an event to the anchors themselves using

$('#modal-name').on('click', 'a', function(event) {
    event.preventDefault();$(this).attr('href'), '_blank');