user1505209
user1505209

Reputation: 291

Tweet Button Javascript

I'm trying to make a shortcut function so that if somebody presses Alt+T they can tweet the article. I have the shortcut part sorted so ignore that part, it's just tweeting the title and URL of the page. Here's what I have so far

<script type="text/javascript">
shortcut.add("Alt+T",function() {
window.open("https://twitter.com/intent/tweet?text=(document.title) - &url=(document.URL)&via=jamiebrittain")
});
</script>

It seems that document.title and document.url aren't changing to page title and URL. This is all in a script tag stating it's javascript so why is not changing or does document.title and document.url not work?

Upvotes: 0

Views: 425

Answers (1)

Manse
Manse

Reputation: 38147

Instead of

window.open("https://twitter.com/intent/tweet?text=(document.title) - &url=(document.URL)&via=jamiebrittain")

do

window.open("https://twitter.com/intent/tweet?text="+encodeURIComponent(document.title)+"&url="+ encodeURIComponent(document.URL)+"&via=jamiebrittain")

you need to concatenate the string with the javascript variables instead of using them inline.

Thanks @Esailija for pointing out that you need to use encodeURIComponent too - this ensures that the variables are encoded before being added to the string

Upvotes: 2

Related Questions