In this post we will post a tweet using JavaScript. Let us assume we have a button like following
On click event of this button we want to post a tweet. For that we need to navigate to user to URL
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.
txttoTweet is variable containing text to be tweeted. In Else part we can tweet by redirecting to said URL as following,
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,
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
On successfully sign in you should be able to tweet.
In this way you can tweet using JavaScript. I hope this post was useful. Thanks for reading.
Follow @debug_mode