Am I overthinking the Twitter button in the Quote Machine?

Hi All,

I almost have the quote machine done, but I’m not sure if I’m approaching the Twitter button the right way.

For my HTML I currently have this…

<a class="float-left" href="#" target="_blank"><i class="fa fa-twitter-square" aria-hidden="true"></i></a>

I believe I need the ?text bit to actually have the quote show up when I click on the Twitter icon; however, I need to somehow load in that text into this URL when a user clicks the Twitter icon.

So with that I tried using some JS to load that into the href so I have this…

 var tweetMsg;
  $.ajax ( {
    type: 'GET',
    url: '[orderby]=rand&filter[posts_per_page]=1',
    success: function ( data ) {            
      tweetMsg = $( ".message" ).html( '<blockquote><h3>' + data[0].content + '</h3></blockquote>' );
      $( ".author" ).html( '<strong> &ndash;' + data[0].title + '</strong>' );
    error: function () { 
      $( ".message" ).html( '<h3>Dev messed it up!</h3>' ) 
    cache: false
  } );  // end ajax  
$( "a" ).attr("href", "" + tweetMsg);

	} ); // end btn

But after testing this it doesn’t look like the var tweetMsg actually captures the quote. So am I overthinking this? Am I on the right track? If so how would I be able to store the value of the quote in a variable or would I use something else?


Do you have a codepen or something similar that we can see the full code at?


The first problem I could see happening is that, at the time of the href attribute being set (on line 17), tweetMsg doesn’t have a value (it will get a value once the success handler has been called starting on line 8, but the href attribute will be set before then with a blank value).
More or less this is the sequence of events that would happen with this code:

  1. tweetMsg is declared but given no value (line 4).
  2. An ajax request is sent off to your quote API. After the request is sent, execution continues again on line 17 and does not wait for a response before moving on (when a response is received it’ll call the success handler when it is done executing the rest of the code).
  3. All anchors’ href attributes are set to "" + tweetMsg on line 17. Keep in mind that your success handler hasn’t been called, so tweetMsg still has no value.
  4. When a response from the quote API is received, your success (or error) handler is called, and tweetMsg is finally given a value. The only problem is that the href has already been set in step 3 (line 17), so nothing is done with tweetMsg.
    To fix this, I would set the href attribute inside your success handler.

Second, when tweetMsg is given a value, the value it’s being set to the result of ( ".message" ).html( '<blockquote><h3>' + data[0].content + '</h3></blockquote>', which will not be a string as I think you’re expecting (I believe the result will point to your .anchor element, but I could be wrong there).
I think what you want to be doing is setting tweetMsg to data[0].content, which is a string.

Finally, you’ll need to encode anything you put in the Twitter URL using encodeURIComponent, which will convert things like spaces and other characters to tokens that play nicely in URLs.

Sorry for the wall of text, but I wanted to explain my points well to help you see what’s going on in the code.

Let me know if I didn’t explain clearly enough.

EDIT: The code in your post looks slightly different then the code in your Codepen, my post is referring to the code in the OP. (I added line numbers to my post to make it easier to hopefully follow along)


I don’t think the ?text= part of the url is intended to receive HTML markup like this. It’s literally just text, the text that will prepopulate the tweet. See and

1 Like

I also had problems getting the tweet button to work within ajax, using the json data directly. I’d be interested in learning what I messed up, too.

I don’t know if it’s the best way, but it did work when I had it first display the quote in a div id="quote", then I used jQuery to grab $("#quote").text().trim();, which was then concatenated to the end of the twitter URL.

1 Like

Address what MindOfThomas here has suggested and you should have a functioning Twitter button!

1 Like

Huzzah! I think that was it! I put the attr method in the request and I’m getting some text in the twitter button now!!

I wrapped it in that encodeURI method and now I’m almost there. It’s still bringing across the p tags, but I’m super close now. Thank you!

1 Like

Hey Mind,

One question about encodeURIComponnent. I’ve changed up the code a bit since the first post, but for some reason when I do the tweet I am still getting non alpha characters coming up in the HTML code

There’s no shortcut for greatness.

Shouldn’t encode URI that take care of it or no?

Are you referring to the <p> tags? If so, I would use the replace method to get rid of them.
It looks like you tried something like that with tweetMsg.trim().slice( 3 );

Personally I would go with something like tweetMsg = tweetMsg.replace('<p>', '').replace('</p>', '') to get rid of the tags. It’s a quick fix and I’m sure there’s a nicer way to do it but i usually go for the quick and simple myself.

Let me know if there’s anything else (or if I goofed and didn’t answer what you were asking). It’s looking good so far!

Hey Mind,

I took what you said and applied it. Now I’m trying to take this a step further :smiley:

When the quote is over 144 character I’m cutting it down and concat’ing a … to it, but for some reason when it runs that. The URIencode seems to mess up on non alpha characters (what I was kinda getting at in the last IM). Do you have any idea why it doesn’t convert the non alapha characters when I use the if statement? If it’s shorter than 144 it seems to convert it all. :confused:

The problem you’re having with non-alpha characters (and it shouldn’t be with all non-apha characters, just some like the ellipsis (…)) is that not all characters are legal in a query string. Some characters like period, forward slash, ect. have meaning in URLs already, and if they are put into your query string that will mess up how the URL works. encodeURIComponent will automatically escape most characters, but some can’t be put in raw, and instead have to be put in as their Unicode values. Check out the encodeURIComponent documentation and look at the Description section, it will list the characters which the function can’t escape. You might consider writing a regex to simply remove those characters.

1 Like

(@cugamer is right. I had this nearly typed up when he answered so I’ll post it in case it can help you along.)

Tweets are 140 characters so you’ll need to adjust your numbers for that.

I adjusted the if to check for > 140 characters and adjusted the substr to 0, 137 and I’m getting tweets that end exactly at 0 characters remaining.

I see now what’s you’re talking about with some of those characters. This is one I got “Client: “My wife doesn’t like it”; Designer: “Well then, I don’t like your wife”” which is showing up as <strong>Client</strong>: &#8220;My wife doesn&#8217;t like it&#8221;; <strong>Designer</strong>: &#8220;Well then, I don&#8217;t like you... on Twitter.

The quote API seems to be using funky versions of quotes and apostrophes, and it’s adding <strong> tags in too. Replace the two replace calls on line 11 with

.replace(/<(|\/)p>/g,'').replace(/<(|\/)strong>/g, '').replace(/“|”/g, '"').replace(/’/g, "'")

I’ll explain them…
First of all they use Regular Expressions to make targetting text easier.


Will find all occurrences of <p> and </p>. The (|\/) says that between the < and the p, there might be a /.

.replace(/<(|\/)strong>/g, '')

Does the same thing but for <strong> tags.

.replace(/“|”/g, '"')

Finds occurrences of and and convert them to ".

.replace(/’/g, "'")

Does the same thing but with the apostrophe.

Even though I took the time to write this, I encourage you to see if you can come up with your own alternate (and even better) solution.

EDIT: I should’ve pointed out that you’ll need toremove any other tags the quote API inserts into quotes. I didn’t see any others besides <strong> but if there are you should know how to remove them.

1 Like

The interesting thing is that this doesn’t apply on the lengths that are less than 140 characters. It seems like when I use the substr and add the concat that it does the funkyness with those nonalpha characters :confused:

I figured it out :smiley: nevermind!