2

I am doing FreeCodeCamp's Random Quote Machine exercise.

Using this answer, I tried to set up my tweet button to open up a new window rather than a tab that the user could use to Tweet this quotes with.

The only issue is is that it is opening up a new tab as well as a new window. Is there any way I could get it to just open the new window?

HTML for Tweet Link

<a class="twitter-share-button" href="https://twitter.com/intent/tweet" target="_newwin">
Tweet</a>

Related JavaScript

jQuery('a[target^="_newwin"]').click(function() {
    var width = 500;
    var height = 300;
    window.open(this.href , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
});

Pen of my Project

Thank you!

Community
  • 1
  • 1
salad_bar_breath
  • 271
  • 4
  • 18
  • At a guess the new window (or tab) is opened because of the default behavior of the anchor, try http://stackoverflow.com/questions/3786898/jquery-anchor-preventdefault – yuriy636 Aug 17 '16 at 18:23
  • 1
    An easy workaround is to just add `onclick="return false;"` to your anchor. – Steven B. Aug 17 '16 at 18:26

1 Answers1

4

You are getting both your custom behavior (opening a new window) and the standard behavior of a link (in most browser nowadays, opening a new tab). To prevent the latter, you need to use the ´preventDefault´ method:

jQuery('a[target^="_newwin"]').click(function(e) {
    e.preventDefault();
    var width = 500;
    var height = 300;
    window.open(this.href , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
});
Martin
  • 7,634
  • 1
  • 20
  • 23