user3711262
user3711262

Reputation: 61

onClick="window.location -- trying to change to open link in new tab

Just trying to make this current code open the link in a new tab. Tried fixes found on this site for similar problems but haven't been able to get it working yet...

Current working code is:

<div onClick="window.location='https://URL';" class="element _element element-4"></div>

From researching, I've heard I should change it to onClick=window.open so I've changed this now to:

<div onClick=window.open(https://URL, Name) class="element _element element-4"></div>

Problem is, when I do change the code to window.open (as per above) clicking the link doesn't do anything at all now, let alone open in a new tab.

Is it something to do with /div? Do I need to alter the CSS or JS? Any help greatly appreciated! :)

Upvotes: 4

Views: 90207

Answers (4)

wec
wec

Reputation: 235

As Pedro Estrada said in their comment, the reasonable way to solve this is with a real link:

<a href="https://example.com/" target="_blank"></a>

If you need the block layout of a <div>, style the link with display: block.

Real links have a number of useful features that fake JS hacks lack:

  • They can be opened in a new tab or new window, as the user desires
  • You can see where the link points before opening it
  • You can copy the link (or any other feature in the browser right-click menu)
  • Screen readers treat <a>s as links. Trying to copy this with JS will be fragile and buggy.
  • If your JS fails to load or your user doesn't have JS enabled, the link still works
  • Your website is faster to load and faster to run because it doesn't rely on JavaScript to poorly ape a feature that the browser has already implemented

Upvotes: 0

MAFAIZ
MAFAIZ

Reputation: 691

<span 
   class="pseudolink" 
   onclick="location='https://jsfiddle.net/'">
Go TO URL
</span>

.pseudolink { 
   color:blue; 
   text-decoration:underline; 
   cursor:pointer; 
   }

https://jsfiddle.net/mafais/bys46d5w/

Upvotes: 2

SilenceHost
SilenceHost

Reputation: 116

I guess that you've called the function in a wrong formula. Please check your function's parameters.

You can see more details here.

e.g. that works: onClick="window.open('yourURL');"

Upvotes: 11

David Atchley
David Atchley

Reputation: 1204

You need to be passing in the url and name as strings:

window.open("https://amazon.com", "amz");

see if the helps.

However, users can change settings on some browser to affect the way opening a new window or clicking on a link behaves (see target attribute in reference for links). So, you may not always get the desired result depending on the user's settings and browser choice.

Upvotes: 4

Related Questions