Alexander Ramadan

Where I Sometimes Write Stuff

How to Tweet a Page with a Changing Title

I was recently building a page where the main text of the page changed every X seconds. I wanted to have a "Tweet" button on the page so that users could tweet whatever the current text on the page at the time.

The problem with this is that the tweet button functionality didn't provide a straight forward way for me to do this (that I could find).

Twitter does give you the option to tweet the Title of the page, so I decided to leverage this and just tweet the Title of the page. But that didn't solve my problem right away, as the Title of the page at this point was static.

I decided to have the entire page reload, instead of just the container containing the text. I then had to make sure that when the page reloads, the title of the page reflects the current text on the page.

Here is the javascript to generate the random text that displays to the screen

var favorites = ["phrase 1", "phrase 2", "phrase 3", "phrase 4", "phrase 5" ]; var pick_fav = favorites[Math.floor(Math.random() * favorites.length)]; var post_choice = pick_fav

I needed to set the document.title to the variable post_choice which contained the text I wanted to be tweeted.

Doing this was easy

document.title = post_choice

Now every time the page reloads, the title resets to whatever random phrase was chosen with my javascript script above, and when the tweet button is clicked the current title is reflected in the tweet body.

Sidenote, as an SEO I would never deploy a strategy like this on a page that I was trying to optimize. The problem with this is when your page is indexed by Google there is no way to tell which title tag will end up getting indexed for your page since it keeps changing, which could cause your page not to rank. I would only use this on a page where driving organic traffic to it was not a priority.