Best Practice for JS - window.open() in href or in onclick?
45,658
Solution 1
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.
Solution 2
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;
}
Author by
4wk_
Apparently, I prefer to keep an air of mystery about me.
Updated on December 09, 2020Comments
-
4wk_ over 3 years
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.
-
dwjohnston almost 4 yearsWhy is this the better practise?
-
T.J. Crowder almost 4 years@dwjohnston - It's semantic, so the browser (/screen reader, etc.) can indicate what's going to happen, and no JavaScript is required.