Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to simulate target="_blank" in JavaScript ?
The target="_blank" attribute opens links in a new tab or window. In JavaScript, you can simulate this behavior using the window.open() method, which provides more control over how new windows are opened.
The window.open() method is a built-in JavaScript function that opens URLs in new browser windows or tabs. It's supported by all modern browsers and offers flexible options for controlling the new window's behavior.
Syntax
window.open(URL, name, specs, replace)
Parameters
URL ? The URL to open in the new window. If omitted, opens a blank page.
name ? The window name or target (use '_blank' for new tab).
specs ? Window features like size and toolbar (comma-separated).
replace ? Whether to replace current history entry (boolean).
All parameters are optional.
Using onclick with Links
You can attach window.open() to link click events to simulate target="_blank":
<html>
<body>
<h2>Simulate target="_blank" in JavaScript</h2>
<a href="#" onclick="openInNewTab()">Open TutorialsPoint in New Tab</a>
<script>
function openInNewTab() {
window.open('https://www.tutorialspoint.com/', '_blank');
}
</script>
</body>
</html>
Using Buttons
Buttons can also trigger new window opening with different URLs:
<html>
<body>
<h2>Open Links in New Windows with Buttons</h2>
<input type="button" onclick="openSite('https://www.tutorialspoint.com/')" value="TutorialsPoint">
<br><br>
<button type="button" onclick="openSite('https://www.google.com')">Google</button>
<script>
function openSite(url) {
window.open(url, '_blank');
}
</script>
</body>
</html>
Programmatic Window Opening
You can also open windows programmatically without user interaction:
<html>
<body>
<h2>Programmatic Window Opening</h2>
<button onclick="openMultiple()">Open Multiple Sites</button>
<script>
function openMultiple() {
// Open multiple windows
window.open('https://www.tutorialspoint.com/', '_blank');
window.open('https://www.w3schools.com/', '_blank');
}
</script>
</body>
</html>
Key Points
- Use
'_blank'as the second parameter to open in a new tab - Modern browsers may block programmatic popups without user interaction
- Always provide fallback behavior for blocked popups
- Consider user experience when opening multiple windows
Conclusion
JavaScript's window.open() method effectively simulates target="_blank" behavior with greater flexibility. Use it with onclick events for links and buttons to control how new windows open in your web applications.
