Created
August 12, 2024 23:33
-
-
Save AliAlmasi/a8b50b0f531e1fa87f089569067800fe to your computer and use it in GitHub Desktop.
A good way to navigate the user to a new tab (without using `location.replace` or `window.open`) in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function newtab(href) { | |
let a = document.createElement("a"); | |
a.href = href; | |
a.setAttribute("target", "_blank"); | |
a.click(); | |
a.remove(); | |
} | |
// You can use it like this: | |
document.querySelector("span").addEventListener("click", () => newtab("http://al1almasi.ir")); | |
// or like this in HTML: | |
<span onClick="newtab('http://al1almasi.ir');" style="cursor:pointer">Click me</span> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment