Skip to content

Instantly share code, notes, and snippets.

@AliAlmasi
Created August 12, 2024 23:33
Show Gist options
  • Save AliAlmasi/a8b50b0f531e1fa87f089569067800fe to your computer and use it in GitHub Desktop.
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
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