Para que possamos testar o funcionamento do mesmo, iremos precisar de 3 arquivos: um arquivo com o código HTML, outro com o JavaScript e o outro com o CSS da página. Os arquivos CSS e JS são linkados diretamente na tag head do arquivo HTML ou você pode configurar o funcionamento do código de acordo com a sua página.
HTML - twitter.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <title>Retornando tweets com JQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script> <link href="twitter.css" rel="stylesheet" type="text/css" media="screen" /> <script src="twitter.js"></script> </head> <body> <div id="tweetroll"> <h1>Twitter Feeds</h1> <div class="loading">Carregando tweets...</div> </div> </body> </html>
CSS - twitter.css
* { padding: 0; margin: 0; } #tweetroll { margin: 0 auto; margin-top: 20px; margin-bottom: 20px; width: 400px; font-size: 15px; font-family: "Trebuchet MS", Arial, sans-serif; color: #333333; background: #fff; border: 5px solid #f90; } #tweetroll .tweet { padding: 10px; border-bottom: 1px dotted #ccc; } #tweetroll .loading { padding: 10px; border-bottom: 1px dotted #ccc; } #tweetroll .tweet a { text-decoration: none; color: #036; } #tweetroll .tweet a:hover { text-decoration: underline; } #tweetroll .tweet .time { font-size: 10px; font-style: italic; color: #666666; } #tweetroll h1 { display: block; padding: 10px; background: #f90; color: #fff; }
JavaScript / JQuery - twitter.js
JQTWEET = { // Coonfigurar nome de usuário do twitter, número de tweets & id/class onde serão exibidos os tweets user: 'kalcarvalho', //mude para o seu nome de usuário do twitter numTweets: 7, //número de tweets que deverão ser retornados appendTo: '#tweetroll', //onde os tweets serão inseridos // função principal do JQTWEET loadTweets: function() { $.ajax({ url: 'http://api.twitter.com/1/statuses/user_timeline.json/', type: 'GET', dataType: 'jsonp', data: { screen_name: JQTWEET.user, include_rts: true, count: JQTWEET.numTweets, include_entities: true }, success: function(data, textStatus, xhr) { var html = '<div class="tweet">TWEET_TEXT<div class="time">AGO</div>'; $(".loading").css('display','none'); // inserindo tweets na página for (var i = 0; i < data.length; i++) { $(JQTWEET.appendTo).append( html.replace('TWEET_TEXT', JQTWEET.ify.clean(data[i].text)) .replace(/USER/g, data[i].user.screen_name) .replace('AGO', JQTWEET.timeAgo(data[i].created_at)) .replace(/ID/g, data[i].id_str) ); } } }); }, /** * Calculadora relativa do tempo para o TWITTER * @param {string} data do tweet retornada da API do Twitter * @return {string} tempo relativo como "2 minutos atrás" */ timeAgo: function(dateString) { var rightNow = new Date(); var then = new Date(dateString); if ($.browser.msie) { // IE can't parse these crazy Ruby dates then = Date.parse(dateString.replace(/( \+)/, ' UTC$1')); } var diff = rightNow - then; var second = 1000, minute = second * 60, hour = minute * 60, day = hour * 24, week = day * 7; if (isNaN(diff) || diff < 0) { return ""; // Retorna vazio se a data não for conhecida. } if (diff < second * 2) { // até 2 segundos return "agora"; } if (diff < minute) { return Math.floor(diff / second) + " segundos atrás"; } if (diff < minute * 2) { return "há 1 minuto atrás"; } if (diff < hour) { return Math.floor(diff / minute) + " minutos atrás"; } if (diff < hour * 2) { return "há 1 hora atrás"; } if (diff < day) { return Math.floor(diff / hour) + " horas atrás"; } if (diff > day && diff < day * 2) { return "yesterday"; } if (diff < day * 365) { return Math.floor(diff / day) + " dias atrás"; } else { return "mais de um ano atrás"; } }, // timeAgo() /** * The Twitalinkahashifyer! -- Converte #hashtag, links e menção * http://www.dustindiaz.com/basement/ify.html * Eg: * ify.clean('your tweet text'); */ ify: { link: function(tweet) { return tweet.replace(/\b(((https*\:\/\/)|www\.)[^\"\']+?)(([!?,.\)]+)?(\s|$))/g, function(link, m1, m2, m3, m4) { var http = m2.match(/w/) ? 'http://' : ''; return '<a class="twtr-hyperlink" target="_blank" href="' + http + m1 + '">' + ((m1.length > 25) ? m1.substr(0, 24) + '...' : m1) + '</a>' + m4; }); }, at: function(tweet) { return tweet.replace(/\B[@ï¼ ]([a-zA-Z0-9_]{1,20})/g, function(m, username) { return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/intent/user?screen_name=' + username + '">@' + username + '</a>'; }); }, list: function(tweet) { return tweet.replace(/\B[@ï¼ ]([a-zA-Z0-9_]{1,20}\/\w+)/g, function(m, userlist) { return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/' + userlist + '">@' + userlist + '</a>'; }); }, hash: function(tweet) { return tweet.replace(/(^|\s+)#(\w+)/gi, function(m, before, hash) { return before + '<a target="_blank" class="twtr-hashtag" href="http://twitter.com/search?q=%23' + hash + '">#' + hash + '</a>'; }); }, clean: function(tweet) { return this.hash(this.at(this.list(this.link(tweet)))); } } // ify }; $(document).ready(function () { // start jqtweet! JQTWEET.loadTweets(); });
Você pode verificar um exemplo desse código em funcionamento clicando aqui.
Um abraço a todos e até o próximo post!
Nenhum comentário:
Postar um comentário