How to Post a Tweet using JavaScript

In this post we will post a tweet using JavaScript. Let us assume we have a button like following

image

On click event of this button we want to post a tweet. For that we need to navigate to user to URL

image

After status we can put text to be tweeted. So on click event we need to navigate to this URL and append text to be tweeted. Very first we need to check whether tweet length is less than 140 or not. If it is more than 140 then we will show error message to user.

image

txttoTweet is variable containing text to be tweeted. In Else part we can tweet by redirecting to said URL as following,

image

Full code is as following,

<html>
<head>
 <title>
 </title>
 <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js">
</script>
 <script type="text/javascript">
 $(document).ready(function () {
 $('#btnTweet').click(function (e) {
 alert('hello11');
 var textToTweet = "Hi I am tweeting from here";
 if (textToTweet.length > 140) {
 alert('Tweet should be less than 140 Chars');
 }
 else {
 var twtLink = 'http://twitter.com/home?status=' +encodeURIComponent(textToTweet);
 window.open(twtLink,'_blank');
 }
 });
 });

</script>
 <style type="text/css">
 #btnTweet {
 width: 159px;
 height: 38px;
 }
 </style>
</head>
 <body>
 <h1>tweet from debugmode</h1>
 <button id="btnTweet">Tweet</button>
 </body>
</html>

Some of the important point worth discussing here is as following,

  • Text to Tweet must be inside encodeURIComponet . Else you will get error.
  • Check Text to Tweet is less than 140 characters.
  • If you want can open windows as dialog also.

On running above script you should be getting output as following,

image

On click of Tweet button in next tab or windows as of your browser setting you will be asked to log in to Twitter, if not already logged in

image

On successfully sign in you should be able to tweet.

image

In this way you can tweet using JavaScript. I hope this post was useful. Thanks for reading.

Dhananjay Kumar is Developer, Blogger , Speaker, Learner , Mindcracker & Microsoft MVP.

Posted in Web

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my current or previous employer's view in anyway. © Copyright 2013
Follow

Get every new post delivered to your Inbox.

Join 2,121 other followers

%d bloggers like this: