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?
I would start with moving the $("#postTweet").click();
event out from the $.ajax();
and getQuote()
function.
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.
Not sure if you solved it already, but you might want to use unbind()
here. Like: $("myButton").unbind().click(function(){ ... });
@BenGitter
unbind() works too, but jquery recommends .off now, as unbind has been deprecated.
1 Like
I just checked, looks like moving $("#postTweet").click();
event solved the problem.