0

I am using a javascript function to navigate away from my website and to another website. I am also trying to open a new page when the button is clicked but instead it navigates on self instead of blank. Why does this happen?

HTML

<p style="text-align:center;">
<input style="font-size:large;" id="btamen" type="button" value="Visit Website">
</p>

JavaScript

<script type="text/javascript">
$("#btamen").click(function() {
    window.location.href = 'http://www.google.com'

    link.target = '_blank';
});
</script>
Skullomania
  • 2,225
  • 2
  • 29
  • 65
  • Just use google ;) http://stackoverflow.com/questions/19851782/how-to-open-a-url-in-a-new-tab-using-javascript-or-jquery – Bluedayz May 03 '14 at 15:07

2 Answers2

2

This line: window.location.href = 'http://www.google.com' will always replace current page with the new url.

I don't know what is link in the next page, but that code won't even execute because the page redirects and the context is lost.

If you want it like that, then do this:

window.open('http://www.google.com', '_blank').focus();

Also, you cannot guarantee its opening as browser might block it. Sort of kinda pop up blocker.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
1

I don't think you can control it to open in a new tab. So you have to work around, what I did is:

<a href="" target="_blank" id="btamen_link">
  <button type="button" id="btamen">
    Click
  </button>
</a>

And the jquery:

<script type="text/javascript">
  $(document).ready(function(){
    $('#btamen').click(function(){
      $('#btamen_link').attr('href', 'http://www.google.com');
      $('#btamen_link').click();
    });
  });
</script>
adolfotcar
  • 515
  • 2
  • 8