Javascript: location.href to open in new window/tab?
You can open a URL in a new tab using the window.open()
method and specifying '_blank'
as the second parameter:
Here, window.open()
is the savior that triggers a new tab with your specified URL.
Creating clickable links with JavaScript
Create and simulate a click on a dynamic <a>
element to open a new tab. This can be particularly useful when you want to open a link in response to non-click events:
This is like creating an invisible hand that clicks a link for the user. More importantly, this method has a better chance of bypassing the foes of popups, the popup blockers.
Full URLs are essential
While using window.open()
, always provide the URL in its entirety, including the protocol (http or https). Else, you might fall into the bottomless pit named unexpected behavior:
Remember, unexpected things are fun, but not when coding!
Stimulate programmatic navigation
Add an id
to an <a>
element and give the power to JavaScript to decide when to navigate:
AbraKadabra! Now, this link obeys JavaScript's command and opens when Bennet feels it's the right time.
Consider the user experience
Don't forget that you are not alone in the game, there's another player – the user! So, before you surprise them with 50 new tabs, take time to judge the intrusiveness of your actions:
Beware of popup blockers
Popup blockers may seem like villains. But in truth, they are superheroes saving users from unwanted popups. When riding on window.open()
, ensure you have the permit or at least come clean to your users:
User attention matters
Opening multiple tabs/windows automatically can overwhelm the user turning them into a 🧟♂️. Hence, only spawn new tabs if they bring value to your user's workflow:
Think of accessibility
Accessibility is a big game player! Make sure your site doesn't throw curveballs at users using screen readers and other assistive technologies. Spoiler alert: They might not handle multiple windows graciously! 🕊️
Being explicit is the best policy!
Was this article helpful?