Window.open and click event: multiple tabs are opened while only one should

Window.open and click event: multiple tabs are opened while only one should
0

#1

So I noticed a bug on my quotemachine project, a click event should be opening only one tab but opens multiple ones.

After the “get a quote” button is pressed at least once, if you press the “share on twitter” button, multiple twitter tabs open, but only one is intended.

Here’s the project link: http://codepen.io/fabricioch/pen/ZBYaOa

And here’s the part of the code related to the click event:

$("#postTweet").click(function(){
          var twitterURL = 'https://twitter.com/intent/tweet?hashtags=quotes&   related=freecodecamp&text=' + encodeURIComponent(quote + author);
      window.open(twitterURL);
});

The bug only happens after the “get a new quote” button is clicked at least once.

Can you spot what is causing the bug?


#2

I would start with moving the $("#postTweet").click(); event out from the $.ajax(); and getQuote() function.


#3

This did it @jamesperrin

It appears as though each time an event listener is added it accumulates, so when the user finally clicks the button, if the event listener was added y times, y tabs are opened.

So if something like

$("#myButton").click(function(){
            myFunction();
});

$("#myButton").click(function(){
            myFunction();
});
$("#myButton").click(function(){
            myFunction();
});

is in the code, when #myButton is clicked, myFunction() is executed 3 times exactly.


#4

Not sure if you solved it already, but you might want to use unbind() here. Like: $("myButton").unbind().click(function(){ ... });


#5

@BenGitter

unbind() works too, but jquery recommends .off now, as unbind has been deprecated.


#6

I just checked, looks like moving $("#postTweet").click(); event solved the problem.