Javascript code weird bug

Closed
3rabii3 Posts 2 Registration date Monday January 18, 2021 Status Member Last seen February 20, 2021 - Updated on Jan 18, 2021 at 08:31 AM
 Od1n - Aug 30, 2021 at 06:50 PM
Hi, I use a Javascript code to open a link in new tab when a button is clicked. I use this function:
<button  onclick="myFunction()">Open site</button>
<script>
function myFunction(){
  window.open("LINK");
}
</script>

The problem is there is a bug in links it open the wrong links like if I clicked the other button, it mixes the links. This happens if the codes are in the same page. I searched google for this probleme but i don't find. Any idea about this weird thing?
How can I put my buttons in home page without having this bug?

Thank you,

1 response

Hi
first why use a button for a simple link?

You can easily use a a tag with href=your link...
it'll be way better and no need of adding a layer of programming and just need to style the a tag with some CSS using border radius and any fancy you need.

second: you can do it using a button and some script...even if it'sd more complicated and useless(see 1st solution) but you'll have to use a parameter and by the way don't write the link in hard write into the function:


function goLink(linkURL){
  window.open(linkURL);
}


<button  onclick="golink('http:google.com')">Open site</button>


Or even better using addEventListener which is the right way to do it(because you separate code from HTML and use the right event drivcen way to do).

<button  id="mybt">Open site</button>


getElementById('mybt').addEventListener('click', goLink('http:google.com'));


In this last example you can even remove the link if you need, it's easier to read and use it separate from HTML(so to any page you need it) but sure the usual <a href ...
in this case is way better and no need to add JavaScript who'll slow and complicate thing for nothing.
1