Tutorial on how to Share quote on Twitter using Javascript and HTML

Hi,

Is there any guide on how to use Javascript to share a quote on Twitter?

It is a steep learning curve after completing the tutorials on freeCodeCamp…

Some people suggested using data attribute but I have no clue how to apply that after reading through the documentation.

I also read through the Twitter documentation but not sure how to modify the URL ( ?text= ) to add the quotes after the “=” using Javascript.

Hey @E-Mech

Please share you Codepen if you have attempted to make the App so that I can guide you properly. For an Idea on how it can be done you can have a look at the below code.

var tweetUrl = "https://twitter.com/intent/tweet?text="+quote+" By "+authorName;

Notice the quote & authorName variables, These variables contain the data that needs to be attached to the URL. So using string concatenation method we can easily combine the URL and the data.

Here is my code: https://codepen.io/emech/pen/EWoqQV

I could not figure out how to insert the concatenated URL and quote into the href="";
I tried using getElementByID but it appears as a text for the link generated.

Here look at this forked & edited pen of yours. https://codepen.io/nawazish/pen/LWmywO?editors=1010

DId you just add this line:?
document.getElementById(‘tweet-share’).setAttribute(“href”, tweetUrl);
}

Nice! Thanks! I’m not familiar with this javascript functions.

1 Like

Yeah you got it. Let me explain if you didn’t get it. For anchor tag to work you need point the href attribute to desired url and that’s what this code is doing.

you can read more about setAttribute here.

1 Like

This can be reverse engineered from the sample. Find what the Twitter link points to by hovering or clicking, split apart the URL, replace the quote/author with variables representing the data you pulled from the API, and concatenate.

Here’s mine for reference:
http://codepen.io/lionel-rowe/pen/WpOpgR

I didn’t look into the example code because I thought that we are not allowed to do so… I’m not really sure how the reverse engineer term is defined in this context

Reverse engineering means analysing the end product and figuring out how to make it work, not looking at the source code and copying it. It’s true the lines are a bit more blurred when everything’s front end, but if you’re copying stuff it’s not truly “reverse engineering”.

In this case, as I mentioned, you can find the URL by hovering or clicking on the link. Then you just have to work out which part(s) are variables and how to get them using the API you’ve chosen.