Vy Do
Vy Do

Reputation: 52488

Why hyperlink not open in new tab?

I have 3 file html: force_hyperlink_open_in_new_window.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Force hyperlink open in new window</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

</head>
<body>
<a href="force_hyperlink_open_in_new_window_01.html">Foo</a>
<a href="force_hyperlink_open_in_new_window_02.html">Bar</a>

<script type="text/javascript">
    $('a[href^="http://"]')
            .not('[target="_blank"]')
            .attr('target', '_blank');
</script>

</body>
</html>

force_hyperlink_open_in_new_window_01.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>01</title>
    <style>
        body{
            background-color: tomato;
        }
    </style>
</head>
<body>
</body>
</html>

force_hyperlink_open_in_new_window_02.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>02</title>
    <style>
        body{
            background-color: limegreen;
        }
    </style>
</head>
<body>
</body>
</html>

Why 2 hyperlinks don't open in new tab (I use Google Chrome Version 52.0.2743.116 (64-bit))?

Upvotes: 0

Views: 330

Answers (3)

mxlse
mxlse

Reputation: 2784

You select anchors starting with http:// while your links are relative and don't start with http://.

Change the JQuery selector to general anchors: $('a') and it will add your target, if they don't already have it. See https://jsfiddle.net/k7ww81ee/

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

Upvotes: 2

Maciej Sikora
Maciej Sikora

Reputation: 20132

Your href does not match they not have http.

Change:

$('a[href^="http://"]')

to

$('a')

to grep all links.

Upvotes: 1

Mko
Mko

Reputation: 148

Could be because the hrefs don't start with http://. Also, you can force opening links in new tabs by putting this line in head:

<base target="_blank" />

Upvotes: 2

Related Questions