When building a website, sometimes you want a link to open in a new tab while keeping the user on the same page. This is especially useful when linking to external websites, documents, or resources, so visitors don’t lose their current browsing session.
In this post, we’ll show you how to achieve this using simple HTML and JavaScript.
1. Using target="_blank":-The simplest way to open a link in a new tab is by using the target="_blank" attribute in your <a> tag.
<a href="http://example.com/" target="_blank">Open New Link</a>
2. Using JavaScript window.open() :-
To open a link in a new tab while ensuring the user stays on the same page, you can use JavaScript’s window.open() method along with an onclick event.
Here’s the example code:
<a href="http://example.com/" target="_blank" onclick="window.open('http://example.com/'); return false;">Open New Link</a>
3. Explanation of Code:-
href="http://example.com/"→ Provides the link destination.target="_blank"→ Ensures the link opens in a new tab.onclick="window.open(...)"→ Uses JavaScript to open the link in a new tab.return false;→ Prevents the default behavior of navigating away from the current page.
So, when the user clicks the link, the new page opens in a separate tab, but the current page remains open as it is.
4. Final Example
Here’s a complete working example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Open Link in New Tab</title>
</head>
<body>
<p>Click the link below to open it in a new tab without leaving this page:</p>
<a href="http://example.com/" target="_blank" onclick="window.open('http://example.com/'); return false;">Open New Link</a>
</body>
</html>
No comments:
Post a Comment