Click here to Skip to main content
14,828,290 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I use a Javascript code to open a link in new tab when a button is clicked. I use this button:
HTML
<button  onclick="myFunction()">Link1</button>
JavaScript
function myFunction(){
  window.open("Link1");
}

And in another post in the home page of my blog, I put another button:
HTML
<button  onclick="myFunction()">Link2</button>
JavaScript
function myFunction(){
  window.open("Link2");
}

The problem is, when I click the button to go to Link1, it opens Link2.

How can I put my buttons all in home page without having this bug?

Thank you,

What I have tried:

I tried to put each button in a different page then it works. But i want to put all my buttons in same page.
Posted
Updated 18-Jan-21 4:31am
v2
Comments
Richard MacCutchan 18-Jan-21 10:06am
   
Use different function names.
Rabiî Ab 18-Jan-21 11:13am
   
Different function names didn't work.

1 solution

Option 1
Rather than using a <button>, use an <a> tag with target="_blank". You can use CSS to style the link to look like a button if required.
HTML
<a href="Link1" target="_blank">Link1</a>
<a href="Link2" target="_blank">Link2</a>
JavaScript
// No Javascript required...

Option 2:
Use a different function name for each button, as suggested by RMC in the comments.
HTML
<button onclick="openLink1();">Link1<button>
<button onclick="openLink2();">Link2<button>
JavaScript
function openLink1(){
    window.open("Link1");
}
function openLink2(){
    window.open("Link2");
}

Option 3:
Use a single function for all buttons, and an argument to the function to specify which URL to open.
HTML
<button onclick="myFunction('Link1');">Link1<button>
<button onclick="myFunction('Link2');">Link2<button>
JavaScript
function myFunction(url){
    window.open(url);
}
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900