Do Nhu Vy Do Nhu Vy - 3 months ago 9
HTML Question

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))?

Answer

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');
Comments