Quote Generator: Trouble setting tweet text using attr()

I’m having trouble getting the current quote to appear in the tweet. The .attr() method works for retrieving the quote after $(document).ready, but for some reason it doesn’t seem to work within the .on() method. In other words, the default text in the tweet is always the quote that appears when the page loads, it doesn’t adjust to match the quote that appears after pressing the “new quote” button. I can’s see any reason why this would be. Is there something obvious I am missing? I’d appreciate any help or clarity anyone could give. Here is my code:

function selectQuote(){
return quoteArray[Math.floor(Math.random()*quoteArray.length)]

var newQuote = selectQuote();

(document).ready(function(){ (".quote p").text(newQuote);
$(".twitter-share-button").attr(“data-text”, newQuote);

(".new-quote").on ("click", function(){ newQuote = selectQuote(); (".quote p").text(newQuote);
$(".twitter-share-button").attr(“data-text”, newQuote);

Can you post your html also or better yet a link to your project (i.e. Codepen)?


There are a couple of ways to do this, but if you want to still use the majority of your existing code, you will need to take the following steps:

#1) Add the following widgets.js to the Codepen JS external links section.


#2) Add the following function to your JS

function showTweetBtn(q) {
    document.getElementById("tweet"),{size: "small",text: q}

#3) Add a new div with id=“tweet” to your html below the New Quote button

<div id="tweet"></div>

#4) Define the css for your div with id=“tweet” and use inline-block for the display property so it is on the same line as you button

#tweet {

Finally, add the call to the new function under each time you update the quote:

  $(".quote p").text(newQuote);

You can remove the following html code:

<a href="https://twitter.com/share?ref_src=twsrc%5Etfw" class="twitter-share-button" data-text="Quote missing!" data-show-count="false" target ="blank_">Tweet</a> <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

and the following JS code:

$(".twitter-share-button").attr("data-text", newQuote);

Thanks! That works and I at least think I understand why, it makes sense to generate a new tweet button each time.

The thing I still don’t understand is why my .attr() method worked when the page loaded but not after clicking the “new quote” button. Is it something I’m not understanding about the way the .attr() method and the .on() method work?