5

Just a question about optimization, between :

<a href="#" onClick="javascript:window.open('myUrl.com');">link-1</a>

and :

<a href="javascript:window.open('myUrlBis.com');">link-2</a>

Is one better than the other ? Or more compatible ? Thanks.

4wk_
  • 2,458
  • 3
  • 34
  • 46
  • Not really a duplicate of [Onclick or href which is best for opening an link in button](http://stackoverflow.com/questions/10765363/onclick-or-href-which-is-best-for-opening-an-link-in-button) ;) – 4wk_ Jun 12 '12 at 16:39
  • 2
    Neither is preferred. You should look into JavaScript event binding, and listen for the click on the link. – Greg Pettit Jun 12 '12 at 16:39

4 Answers4

17

Best practice is to use the target attribute:

<a href="http://myUrl.com" target="_blank">link-1</a>

If that doesn't suit, a click handler (ideally not assigned via attribute) would be my take.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

Neither one

Make it a regular link using href and target

<a id='my-link' target="_blank" href="http://myUrlBis.com">link-2</a>

If you need to do some processing of the click with JavaScript, you can use the following

document.getElementById("my-link").onclick = function(e) {
  // Do some processing here, maybe 
  window.location = this.href
  // Return false to prevent the default action if you did redirect with script
  return false;
}
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
0

No JavaScript

<a target="_blank" href="myUrlBis.com">link</a>

With JavaScript

<a target="_blank" href="http://www.example.com" id="myLink">link</a>
<script>
    document.getElementById("myLink").onclick = function(){ //attach click event to link
        var winPop = window.open(this.href);  //`this` is reference to link, get href
        return false;  //prevent click event from clicking the link
    }
</script>

JSFiddle Example

epascarello
  • 204,599
  • 20
  • 195
  • 236
-1

Below code should be fine.

<a href="javascript:void(0);"  onclick="window.open(url)">

Found issue in IE (version:11) with below code

<a onclick="javascript:window.open(url)">

Problem: The parent window is getting refreshed in IE when we have javascript window.open code in href attribute.