To let people easily share the patio11bot, we'll add a "Tweet" button to the page. You can easily add a static share button by going to
https://publish.twitter.com/ and following the instructions there, but to make a dynamic tweet button is more difficult.
Instructor: [00:00] Our patio11bot works now. It can take in a question and can produce an answer. Now we want to see if people can share it, which is a great use case for a Tweet button. Let's start out by going to publish.twitter.com.
[00:14] We can scroll down to the Twitter buttons and select the Share button. Then we can copy that code there. Back in our HTML document, we'll paste in the code just above the Ask Another Question button. Let's start by just trying that out.
[00:32] We'll open the site in a browser and ask a question. There's the Tweet button. Let's press that. Up pops the Twitter screen. It's auto-populated with a title of a site, which is patio11bot, and the URL. Since we're developing, we have the localhost URL. In production, online, this will be whichever domain name you're running.
[00:54] Now let's look to customize that. The button accepts many attributes. First, we can make it larger by setting a data-size to large. If you want a specific Twitter user name to appear in the pre-populated tweet, you can set the data-via attribute. Finally, we'll change the default text by setting the data-text attribute.
[01:13] Now let's try that out. The Tweet button is larger now. When we press it, we can see the new text we set up plus the via @ mention. That's great. It works for many cases, but in this case, I'd like to go one step further and include the patio11 quote in the body of the tweet itself.
[01:33] That turns out to be much more complicated than you might expect. You might think, like I did at first, that you could just change this data-text attribute to show the new quote. What's really happening is that the script tag here is loading and changing this a tag into something else altogether.
[01:48] Instead, let's first extract this script and move it up to the head. Then we'll put a div here and give it an id of tweet-button, so we can reference it later. Now let's cut this tweet a tag out altogether and go down to the askquestion function.
[02:05] Here, once the question is asked and the answer is known, we can first find the div that we just made. Then we'll set the innerHTML to the link that we just copied. Now we can change the data-text attribute here based on whatever answer the bot just picked. We can format it a bit by adding some new lines in there. We're almost done.
[02:27] Now we have to tell the Twitter script to load this Tweet button as a widget again since we just put it on the page. We can do that by referencing the Twitter script, which is called twttr and calling widgets.load. That's it.
[02:43] Let's look at this again in a browser. This time, when we press the Tweet button, we see the dynamic formatted message.