Display Latest Tweets JavaScript


/ Published in: JavaScript
Save to your folder(s)

Display the latest tweets of a user using JavaScript. Not really a recommended way. If Twitter is slow, your site will load slow. I would recommend using my PHP implementation instead. It will not hang your site if Twitter is not working.


Copy this code and paste it in your HTML
  1. <!-- The HTML -->
  2. <h3>Recent Twitter Updates</h3>
  3. <div id="twitter_update_list"></div>
  4. <script src="twitter.js"></script>
  5. <!-- Make sure you replace username with your Twitter username -->
  6. <script src="http://twitter.com/statuses/user_timeline/username.json?callback=twitterCallback2&amp;count=10"></script>
  7. <p><a href="http://twitter.com/username">Follow me</a></p>
  8.  
  9. //The JavaScript file
  10. function twitterCallback2(twitters) {
  11. var statusHTML = [];
  12. for (var i=0; i<twitters.length; i++){
  13. var username = twitters[i].user.screen_name;
  14. var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
  15. return '<a href="'+url+'">'+url+'</a>';
  16. }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
  17. return reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
  18. });
  19. statusHTML.push('<li><span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li>');
  20. }
  21. document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
  22. }
  23.  
  24. function relative_time(time_value) {
  25. var values = time_value.split(" ");
  26. time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  27. var parsed_date = Date.parse(time_value);
  28. var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  29. var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  30. delta = delta + (relative_to.getTimezoneOffset() * 60);
  31.  
  32. if (delta < 60) {
  33. return 'less than a minute ago';
  34. } else if(delta < 120) {
  35. return 'about a minute ago';
  36. } else if(delta < (60*60)) {
  37. return (parseInt(delta / 60)).toString() + ' minutes ago';
  38. } else if(delta < (120*60)) {
  39. return 'about an hour ago';
  40. } else if(delta < (24*60*60)) {
  41. return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  42. } else if(delta < (48*60*60)) {
  43. return '1 day ago';
  44. } else {
  45. return (parseInt(delta / 86400)).toString() + ' days ago';
  46. }
  47. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.